如何解决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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。