Python 3:"NameError:name'function'未定义"

qwe*_*rtz 2 python pycharm python-3.x

运行

def foo(bar: function):
    bar()

foo(lambda: print("Greetings from lambda."))
Run Code Online (Sandbox Code Playgroud)

用Python 3.6.2产生

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
Run Code Online (Sandbox Code Playgroud)

但是,删除类型注释按预期工作.

PyCharm还'function' object is not callable在线发出警告bar().


编辑:正如我对Pieters的回答所述,这个问题提出来了,因为

def myfunction():
    pass

print(myfunction.__class__)
Run Code Online (Sandbox Code Playgroud)

输出<class 'function'>.

Mar*_*ers 7

functionPython中没有定义名称,没有.注释仍然是Python表达式,必须引用有效名称.

你可以改为使用类型提示来表示bar可调用的 ; 用途typing.Callable:

from typing import Callable

def foo(bar: Callable[[], Any]):
    bar()
Run Code Online (Sandbox Code Playgroud)

这定义了一个不带参数的可调用类型,其返回值可以是任何值(我们不关心).

  • 谢谢,我期待它是有效的,因为通过 `print(myfunction.__class__)` 检查函数类会产生 `&lt;class 'function'&gt;`。 (3认同)