Python2:函数抽象类型

Python 2: function abstract type

我有一个接受映射的函数,该映射可以是函数的字典,所以我需要区分它们。通常我使用 collectionsisinstance/issubclass 中的一些 Abstract Base Class 来检查参数类型,但是函数没有 ABC。我知道我可以做到 hasattr(mapping, "__call__"),但我想知道是否有更具体的功能。

您可以使用 callable(obj),它在 Python 2.7 和 Python 3.2+ 中可用,但在 Python 3.0 或 Python 3.1 中不可用。

您也可以使用 types.FunctionType:

isinstance(obj, types.FunctionType)

您可以使用 types module for this which has, among others, FunctionType 定义的:

>>> import types
>>> types.FunctionType
<type 'function'>
>>> def foo(): pass
... 
>>> isinstance(foo, types.FunctionType)
True