在Python中,您如何注释一个接受固定参数以及许多其他参数的函数?
从我的理解来看,在Python中,省略号让您注释一个具有多数参数的函数(在此处找到的文档)。这是我想做的示例:
from typing import Callable, Any
def foo(first: str, *rest: Any):
print(rest)
return first
def call(f: Callable[[str, ...], str]):
f("Hello", 1, None, True)
print(call(foo))
python(或至少,佩莱斯)不喜欢省略号(“ ...”在此上下文中不允许
):
我尝试使用python 3.10的paramspec
s,但是)似乎说它们用于其他目的,我无法说出这些目的是什么。这是我尝试过的:
from typing import Any, Callable, Concatenate, ParamSpec
P = ParamSpec("P")
def foo(first: str, *rest: Any):
print(rest)
return first
def call(f: Callable[Concatenate[str, P], str]):
f("Hello", 1, None, True)
print(call(foo))
Python(或至少是Pylance)似乎反映出它们并不是要使用这种方式:
rel =“ nofollow noreferrer”>
In Python, from my understanding, the ellipsis lets you annotate a function that has any number of arguments (documentation found here). Here's an example of what I'd like to do:
from typing import Callable, Any
def foo(first: str, *rest: Any):
print(rest)
return first
def call(f: Callable[[str, ...], str]):
f("Hello", 1, None, True)
print(call(foo))
Python (or, at least, Pylance) doesn't like the ellipsis ("..." not allowed in this context
):
I've tried to use Python 3.10's ParamSpec
s, but the documentation on them (including PEP 612) seems to say they're used for other purposes, and I can't tell what those purposes are. Here's what I've tried:
from typing import Any, Callable, Concatenate, ParamSpec
P = ParamSpec("P")
def foo(first: str, *rest: Any):
print(rest)
return first
def call(f: Callable[Concatenate[str, P], str]):
f("Hello", 1, None, True)
print(call(foo))
Python (or, at least, Pylance) seems to reflect that they aren't meant to be used this way:
How do I annotate a function like this, that knows the type of one or more of its arguments and accepts any number of other arguments anyway?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
__调用__
在协议
上键入任意功能签名。You can type arbitrary function signatures using
__call__
on aProtocol