如何正确运行注释函数参数
How to properly function annotate function-argument
我希望我的函数被注释为它接受另一个函数作为参数。起初我认为这会很好地工作:
def my_function(func_argument: function):
pass
但是函数是未解析的引用。我查看了内置函数,它确实不存在,这与我通常使用的 str、int 和其他函数不同。但是,它必须在某个地方,因为:
>>> def my_function():
... pass
...
>>> x = my_function
>>> type(x)
<class 'function'>
>>> type(x).__name__
'function'
函数class在哪里定义的,为什么不在内置函数中?我最初的尝试应该是正确的解决方案吗?现在我用 types.FunctionType
注释它,但感觉不对,因为我们在其他任何地方都暗示 str
而不是 types.StringType
。并且只为一个注释导入类型也很奇怪。 typing
图书馆也没有任何可以帮助我替换它的东西。
此外,FunctionType 如何与类型注释强制库一起工作(我看到其中很少有人飞来飞去)
为什么不用Callable
:
Frameworks expecting callback functions of specific signatures might
be type hinted using Callable[[Arg1Type, Arg2Type], ReturnType]
from typing import Callable
def my_function(func_argument: Callable[..., ReturnType]): # replace ReturnType with return type of func_argument
pass
我希望我的函数被注释为它接受另一个函数作为参数。起初我认为这会很好地工作:
def my_function(func_argument: function):
pass
但是函数是未解析的引用。我查看了内置函数,它确实不存在,这与我通常使用的 str、int 和其他函数不同。但是,它必须在某个地方,因为:
>>> def my_function():
... pass
...
>>> x = my_function
>>> type(x)
<class 'function'>
>>> type(x).__name__
'function'
函数class在哪里定义的,为什么不在内置函数中?我最初的尝试应该是正确的解决方案吗?现在我用 types.FunctionType
注释它,但感觉不对,因为我们在其他任何地方都暗示 str
而不是 types.StringType
。并且只为一个注释导入类型也很奇怪。 typing
图书馆也没有任何可以帮助我替换它的东西。
此外,FunctionType 如何与类型注释强制库一起工作(我看到其中很少有人飞来飞去)
为什么不用Callable
:
Frameworks expecting callback functions of specific signatures might be type hinted using
Callable[[Arg1Type, Arg2Type], ReturnType]
from typing import Callable
def my_function(func_argument: Callable[..., ReturnType]): # replace ReturnType with return type of func_argument
pass