How to check for a function type in Python?

后端 未结 4 1011
-上瘾入骨i
-上瘾入骨i 2021-01-13 05:51

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 ty

相关标签:
4条回答
  • 2021-01-13 06:06

    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
    
    0 讨论(0)
  • 2021-01-13 06:09

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

    0 讨论(0)
  • 2021-01-13 06:14

    collections.Callable can be used:

    import collections
    
    print isinstance(f, collections.Callable)
    
    0 讨论(0)
  • 2021-01-13 06:17
    import types
    
    if type(f) == types.FunctionType: 
        print 'It is a function!!'
    
    0 讨论(0)
提交回复
热议问题