How to check for a function type in Python?

2020-03-26 07:26发布

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?

4条回答
家丑人穷心不美
2楼-- · 2020-03-26 08:15
import types

if type(f) == types.FunctionType: 
    print 'It is a function!!'
查看更多
SAY GOODBYE
3楼-- · 2020-03-26 08:16

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).

查看更多
劳资没心,怎么记你
4楼-- · 2020-03-26 08:18

collections.Callable can be used:

import collections

print isinstance(f, collections.Callable)
查看更多
可以哭但决不认输i
5楼-- · 2020-03-26 08:28

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
查看更多
登录 后发表回答