Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

types

I have a function in Python which is iterating over the attributes returned from dir(obj), and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use callable() for this, but I don't want to include classes. The best I've come up with so far is:

isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType))

Is there a more future-proof way to do this check?

Edit: I misspoke before when I said: "Normally you could use callable() for this, but I don't want to disqualify classes." I actually do want to disqualify classes. I want to match only functions, not classes.

like image 426
Joe Shaw Avatar asked Sep 16 '08 16:09

Joe Shaw


3 Answers

Depending on what you mean by 'class':

callable( obj ) and not inspect.isclass( obj )

or:

callable( obj ) and not isinstance( obj, types.ClassType )

For example, results are different for 'dict':

>>> callable( dict ) and not inspect.isclass( dict )
False
>>> callable( dict ) and not isinstance( dict, types.ClassType )
True
like image 114
Matthieu Avatar answered Nov 15 '22 20:11

Matthieu


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.

like image 31
dF. Avatar answered Nov 15 '22 19:11

dF.


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.

like image 40
Jim Avatar answered Nov 15 '22 18:11

Jim