如何指定函数参数的类型 (Python)

Ant*_*kat 4 python generics parameters

我想限制可以作为参数传递给另一个函数的函数的范围。例如,将函数限制为仅两个指定的函数之一,或来自特定模块,或通过签名。我尝试了下面的代码,但其中现在有限制:因为参数可以传递任何函数。

这在Python中可能吗?

def func_as_param():
    print("func_as_param called")


def other_func():
    print("other_func called")


def func_with_func_arg(func: func_as_param):  # this is not giving restrictions
# def func_with_func_arg(func: type(func_as_param)):  # this is also not giving restrictions
    print("func_with_func_arg called")
    func()


def test_func_with_func_arg():
    print("test_func_with_func_arg")
    func_with_func_arg(func_as_param)
    func_with_func_arg(other_func)  # <- here IDE must complain that only func_as_param is expected
Run Code Online (Sandbox Code Playgroud)

小智 5

\n

需要特定签名的回调函数的框架可能会使用以下类型提示Callable[[Arg1Type, Arg2Type], ReturnType]

\n
\n

您可能想使用 Callable 类型。这可能会有所帮助https://docs.python.org/3/library/typing.html#annotating-callable-objects

\n

注意
\nPython 中的类型注释并不像 C 中那样是成败攸关的。它们\xe2\x80\x99 是可选的语法块,我们可以添加这些语法块以使代码更加明确。\n错误的类型注释只会突出显示我们的代码编辑器中的注释不正确 \xe2\x80\x94 不会因注释而引发任何错误。\n如果有必要,您必须自行检查。

\n