14

I've got a list of things, of which some can also be functions. If it is a function I would like to execute it. For this I do a type-check. This normally works for other types, like str, int or float. But for a function it doesn't seem to work:

>>> def f():
...     pass
... 
>>> type(f)
<type 'function'>
>>> if type(f) == function: print 'It is a function!!'
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>>

Does anybody know how I can check for a function type?

1
  • You can also use try/except instead of checking for type. Commented Jul 12, 2013 at 11:02

4 Answers 4

21

Don't check types, check actions. You don't actually care if it's a function (it might be a class instance with a __call__ method, for example) - you just care if it can be called. So use callable(f).

Sign up to request clarification or add additional context in comments.

Comments

5

Because function isn't a built-in type, a NameError is raised. If you want to check whether something is a function, use hasattr:

>>> hasattr(f, '__call__')
True

Or you can use isinstance():

>>> from collections import Callable
>>> isinstance(f, Callable)
True
>>> isinstance(map, Callable)
True

7 Comments

isinstance is not good for isinstance(map, types.FunctionType) returns False. Builtin functions are different not to mention the callable class.
@zhangyangyu For built-in functions, you can use inspect.isbuiltin
There is collections.Callable. It works for buitlin functions too: isinstance(map, collections.Callable) returns True
@stalk - What's the difference between collections.Callable and simply callable (as suggested by DanielRoseman)?
@kramer65 well, i think it just another solution. callable() looks like more simplier.
|
4
import types

if type(f) == types.FunctionType: 
    print 'It is a function!!'

1 Comment

I was trying to get the magic methods, the dunders, to pop up in PyCharm after typing a period and this one worked.
3

collections.Callable can be used:

import collections

print isinstance(f, collections.Callable)

1 Comment

And in new-ish Python 3 versions (I think it's 3.2+) callable is re-introduced as a shorthand for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.