Python 类型提示可使用一种已知位置类型调用,然后使用 *args 和 **kwargs

问题描述

我下面的函数top10,它有:

String[] data = top10.split("#");           // split the elements from the String
List<String> top10List = new ArrayList<>(); // create ArrayList 
Collections.addAll(top10List,data);        // put all the elements to the list

如何输入提示

目前,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 '...'

解决方法

您现在不能像 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,**kwargs) -> None:
    """Some function with one positional arg and then *args and **kwargs."""

foo_: BarFunc = foo