在Python中,您如何注释一个接受固定参数以及许多其他参数的函数?

发布于 2025-01-24 04:08:50 字数 1334 浏览 0 评论 0原文

从我的理解来看,在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): Sceenshot of Pylance hint

I've tried to use Python 3.10's ParamSpecs, 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: Screenshot of Pylance hint

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥有 2025-01-31 04:08:50

您可以使用__调用__协议上键入任意功能签名。

class Foo(Protocol):
    def __call__(self, first: str, *rest: Any) -> str:
        ...

def call(f: Foo):
    f("Hello", 1, None, True)

You can type arbitrary function signatures using __call__ on a Protocol

class Foo(Protocol):
    def __call__(self, first: str, *rest: Any) -> str:
        ...

def call(f: Foo):
    f("Hello", 1, None, True)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文