I have a variable, x, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
>>> isinstance(x, function)
But that gives me:
Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'function' is not defined
The reason I picked that is because
>>> type(x) <type 'function'>
If this is for Python 2.x or for Python 3.2+, you can use
callable(). It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: http://bugs.python.org/issue10518. You can do this with:If this is for Python 3.x but before 3.2, check if the object has a
__call__attribute. You can do this with:The oft-suggested
types.FunctionTypesorinspect.isfunctionapproach (both do the exact same thing) comes with a number of caveats. It returnsFalsefor non-Python functions. Most builtin functions, for example, are implemented in C and not Python, so they returnFalse:so
types.FunctionTypemight give you surprising results. The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container.