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 also 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:
types.FunctionTypes approach is not correct because it fails to cover many cases that you would presumably want it to pass, like with builtins:
>>> isinstance(open, types.FunctionType) False >>> callable(open) True
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. Don't use
types.FunctionType unless you have a very specific idea of what a function is.
Builtin types that don't have constructors in the built-in namespace (e.g. functions, generators, methods) are in the
types module. You can use
types.FunctionType in an isinstance call.
In : import types In : types.FunctionType Out: <type 'function'> In : def f(): pass ...: In : isinstance(f, types.FunctionType) Out: True In : isinstance(lambda x : None, types.FunctionType) Out: True