python 3中的函数注释得到"名称未定义"错误

qed*_*qed 2 typechecking python-3.x

我正在尝试使用python3类型的注释功能.

这是一些没有注释的玩具功能:

def fa(func, *args):
    return func(*args)
def fb(x:str):
    return x + " returned."
fa(fb, "Newton")
Run Code Online (Sandbox Code Playgroud)

这些工作正常.但是一旦我添加了一些注释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
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况?我该如何解决这个问题?

jon*_*rpe 5

正如错误消息告诉您的那样,名称function未定义.如果要将其作为函数提示,请将其放在引号中:

def fa(func: 'function', *args):
Run Code Online (Sandbox Code Playgroud)