python 3 : "NameError: name ' function' is not defined"

标签 python python-3.x pycharm

运行

def foo(bar: function):
    bar()

foo(lambda: print("Greetings from lambda."))

使用 Python 3.6.2 产量

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

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

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


编辑:正如我对 Pieters 回答的评论中所述,提出这个问题是因为

def myfunction():
    pass

print(myfunction.__class__)

输出 <class 'function'> .

最佳答案

Python 中没有定义名称函数,没有。注释仍然是 Python 表达式,并且必须引用有效的名称。

您可以改为使用类型提示来说明 bar 是一个可调用;使用 typing.Callable :

from typing import Any, Callable

def foo(bar: Callable[[], Any]):
    bar()

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

关于 python 3 : "NameError: name ' function' is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46163672/

相关文章:

python - 使用 Python - 从一些 html 中获取表格并显示它?

python - 根据特征工具中的截止时间创建特征

python-3.x - 无法使用Python OpenCV保存修改的框架

python - 我的 Python 进程在哪些 CPU 内核上运行?

Python:IDE 支持输出数据库查询,如 pandas 数据框

python - 如何在Python正则表达式中使用变量

python - 从 groupby pandas 中获取 MultiIndex

python-3.x - 当查询包含来自多个数据库的表的连接时,如何在 boto3 中设置 QueryExecutionContext?

python - 如何在 PyCharm 中正确设置 pipenv?

python-3.x - 如何声明返回对象数组的函数?