Python type hint Callable with one known positional type 然后是 *args 和 **kwargs

Python type hint Callable with one known positional type and then *args and **kwargs

我下面的函数 foo,它有:

from typing import Callable

def foo(bar: str, *args, **kwargs) -> None:
    """Some function with one positional arg and then *args and **kwargs."""

foo_: Callable[[str, ...], None] = foo  # error: Unexpected '...'

我如何输入提示?

目前,mypy==0.812 抛出错误:error: Unexpected '...' [misc]

您现在无法像 Samwise 的评论所说那样执行此操作,但在 Python 3.10(在 PEP 612: Parameter Specification Variables 下)中,您将能够执行此操作:

from typing import Callable, ParamSpec, Concatenate

P = ParamSpec("P")

def receive_foo(foo: Callable[Concatenate[str, P], None]):
    pass

我不确定你是否能够为它声明一个 TypeAlias(因为 P 不能在全局范围内使用),所以你可能必须指定类型每次内联 P

我可能会为此使用协议。它们通常比 Callables 更灵活一些。它看起来像这样

from typing import Protocol

class BarFunc(Protocol):
    def __call__(fakeself, bar: str, *args, **kwargs) -> None:
        # fakeself gets swallowed by the class method binding logic
        # so this will match functions that have bar and the free arguments.
        ...

def foo(bar: str, *args, **kwargs) -> None:
    """Some function with one positional arg and then *args and **kwargs."""

foo_: BarFunc = foo