Python中没有名为function的内置函数,function是types.FunctionType的字符串表示;判断对象是否为函数应使用callable()或isinstance(obj, types.FunctionType)。
Python 里没有叫 function 的内置函数,function 是类型名(type 的一个实例),不是可调用的内置函数。你查不到 help(function),也调用不了 function(...) —— 它根本不是函数。
callable() 和 isinstance(..., types.FunctionType)
想确认某东西是不是函数,别猜,用标准方式:
callable(obj) 最常用:返回 True 表示能加括号调用(包括函数、类、有 __call__ 的实例)types:import types def f(): pass isinstance(f, types.FunctionType) # True isinstance(len, types.FunctionType) # False(len 是 builtin_function_or_method)
types.FunctionType 不涵盖内置函数(如 print、len)、@staticmethod、@classmethod,它们属于不同类型type(lambda: None) 返回什么?为什么不是 function?交互式环境里敲:
type(lambda: None) #注意:这里的
function 是类名显示,不是字符串 'function',也不是可导入的顶层名称。它等价于 types.FunctionType,但你不能直接写 function 当类型用:
isinstance(f, function) → NameError: name 'function' is not defined
isinstance(f, types.FunctionType)
function 这个名字只在 repr 和 __name__ 里出现,不作为内置标识符存在function 当成构造器或类型注解以下写法全错:
f = function(lambda x: x) → NameError(没有这个构造函数)def g(x: function) -> function: → 类型检查器报错(应写 Callable 或 types.FunctionType)from builtins import function → 找不到该名字正确替代方案:
lambda、def、或 types.FunctionT
ype(code, globals, name)(极少见,需字节码知识)from typing import Callable,例如 Callable[[int], str]
真正需要区分函数类型时,types 模块里的具体类型(FunctionType、BuiltinFunctionType、MethodType)比凭名字猜测可靠得多;而日常判断“能不能调用”,callable() 就够了——别被 的显示误导去搜不存在的内置函数。