为 Callable 类型提示指定 *args

Specifying *args for a Callable type hint

指定 Callable 变量 fn*my_args 作为参数的最佳方法是什么?像这样:

def test(fn: Callable([Tuple[any]], None),
         *my_args: any) -> None:
    fn(*myargs)

来自 typing.Callable 上的文档:

There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. Callable[..., ReturnType] (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning ReturnType.

所以在 *args 是可选的并且 ReturnTypeNone 的情况下,使用

fn: Callable[..., None]

P.s。我不使用类型提示,所以如果我有任何误解,请告诉我。

现在 Python 3.10 中的 PEP 612,你可以这样写:

from typing import Callable, ParamSpec

P = ParamSpec("P")


def test(fn: Callable[P, None], *my_args: P.args, **my_kwargs: P.kwargs) -> None:
    fn(*myargs, **my_kwargs)

然后对 test 的任何调用都将进行正确的类型检查。