[英]Python type hint Callable with one known positional type and then *args and **kwargs
我在下面的 function 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.