我下面的函数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
指定内联类型。
关于Python 类型提示 Callable with one known positional type 然后是 *args 和 **kwargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66961423/