python 3: how to check if an object is a function?
11,439
Solution 1
in python2:
callable(fn)
in python3:
isinstance(fn, collections.Callable)
as Callable is an Abstract Base Class, this is equivalent to:
hasattr(fn, '__call__')
Solution 2
How can I check that an object is a function?
Isn't this same as checking for callables
hasattr(object, '__call__')
and also in python 2.x
callable(object) == True
Solution 3
You can do:
def is_function(x):
import types
return isinstance(x, types.FunctionType) \
or isinstance(x, types.BuiltinFunctionType)
Author by
max
Updated on June 03, 2022Comments
-
max almost 2 years
Am I correct assuming that all functions (built-in or user-defined) belong to the same class, but that class doesn't seem to be bound to any variable by default?
How can I check that an object is a function?
I can do this I guess:
def is_function(x): def tmp() pass return type(x) is type(tmp)
It doesn't seem neat, and I'm not even 100% sure it's perfectly correct.