Is there a common way to check in Python if an object is any function type?

if hasattr(obj, '__call__'): pass

This also fits in better with Python's "duck typing" philosophy, because you don't really care what it is, so long as you can call it.

It's worth noting that callable() is being removed from Python and is not present in 3.0.


If you want to exclude classes and other random objects that may have a __call__ method, and only check for functions and methods, these three functions in the inspect module

inspect.isfunction(obj)
inspect.isbuiltin(obj)
inspect.ismethod(obj)

should do what you want in a future-proof way.


The inspect module has exactly what you want:

inspect.isroutine( obj )

FYI, the code is:

def isroutine(object):
    """Return true if the object is any kind of function or method."""
    return (isbuiltin(object)
            or isfunction(object)
            or ismethod(object)
            or ismethoddescriptor(object))

Tags:

Python

Types