HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

How do I detect whether a variable is a function?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfunctiondetectvariablewhether

Problem

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 "", line 1, in ?
NameError: name 'function' is not defined


The reason I picked that is because

>>> type(x)

Solution

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:

callable(obj)


If this is for Python 3.x but before 3.2, check if the object has a __call__ attribute. You can do this with:

hasattr(obj, '__call__')


The oft-suggested types.FunctionTypes or inspect.isfunction approach (both do the exact same thing) comes with a number of caveats. It returns False for non-Python functions. Most builtin functions, for example, are implemented in C and not Python, so they return False:

>>> isinstance(open, types.FunctionType)
False
>>> callable(open)
True


so types.FunctionType might 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.

Code Snippets

callable(obj)
hasattr(obj, '__call__')
>>> isinstance(open, types.FunctionType)
False
>>> callable(open)
True

Context

Stack Overflow Q#624926, score: 1243

Revisions (0)

No revisions yet.