簡體   English   中英

Python 類型提示可使用一種已知位置類型調用,然后使用 *args 和 **kwargs

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

我在下面的 function foo ,它有:

  • 一個具有已知類型的位置 arg
  • 之后可變數量的位置和關鍵字參數
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM