Python 3.x python 3中的函数注释get";“名称未定义”;错误

Python 3.x python 3中的函数注释get";“名称未定义”;错误,python-3.x,typechecking,Python 3.x,Typechecking,我正在尝试使用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

我正在尝试使用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
def-fa(func:function,*args):
返回函数(*args)
def fb(x:str):
返回x+“已返回。”
fa(fb,“牛顿”)
回溯(最近一次呼叫最后一次):
文件“/usr/local/lib/python3.4/site packages/IPython/core/interactiveshell.py”,第2883行,运行代码
exec(代码对象、self.user\u全局、self.user\n)
文件“”,第1行,在
def fa(函数,*args):
NameError:未定义名称“函数”

为什么会发生这种情况?我如何解决它?

因为您在函数参数中定义了一个变量,但该参数在函数外不存在。您必须编写

fa(function=“Newton”)


错误消息告诉您,未定义名称
函数
。如果要将提示作为函数,请将其置于引号中:

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

…因为定义了名称
str
,所以它是内置的。函数不是内置的吗?但是type(fa)是functionTrue,但是名为
function
的类默认情况下不绑定到名称
function
,因为您通常不需要直接访问它(您使用
def
定义函数)。