Python 3中的函数注释出现“name not defined”错误

3
我是一个有用的助手,可以翻译文本。

我正在尝试使用Python3的类型注释功能。

这里是一些没有注释的玩具函数:

def fa(func, *args):
    return func(*args)
def fb(x:str):
    return x + " returned."
fa(fb, "Newton")

这些工作得很好。但一旦我为 fa 添加了一些注释,它就出了问题:
def fa(func:function, *args):
    return func(*args)
def fb(x:str):
    return x + " returned."
fa(fb, "Newton")

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/site-packages/IPython/core/interactiveshell.py", line 2883, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-17-193b74f82e47>", line 1, in <module>
    def fa(func:function, *args):
NameError: name 'function' is not defined

为什么会发生这种情况,我该如何解决?
3个回答

7

正如错误信息所指示的那样,名称function未定义。如果您想将其作为函数提示,请将其放在引号中:

def fa(func: 'function', *args):

因为名称 str 已经被定义,它是内置的。 - jonrsharpe
函数不是内置的?但 type(fa) 是函数。 - qed
是的,但名为“function”的类默认情况下不绑定到名称“function”,因为通常您不需要直接访问它(您使用“def”定义函数)。 - jonrsharpe

0
正如错误信息所述,函数名未定义。如果您想将其作为函数提示,请用引号括起来:
def fa(func: 'function', *args):
除了@johnrsharpe所说的,如果您不想引用名称function,您还可以在Python脚本顶部包含以下行。
# from __future__ imports must occur at the beginning of the file. DO NOT CHANGE!
from __future__ import annotations

-1
因为你在函数参数中定义了一个变量,但是该参数在函数外部不存在。你需要写成:

fa(function="Newton")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接