Python使用默认值用于回调协议参数

发布于 2025-01-25 06:38:33 字数 1055 浏览 1 评论 0原文

我正在尝试为特定的回调协议设置默认值(我希望callback类型的任何回调需要传递参数a,但可选地传递参数<代码> b )。使用以下代码:

from typing import Protocol
from dataclasses import dataclass


class Callback(Protocol):
    def __call__(self, a: str, b: str = "") -> None:
        ...


def foo(a: str, b: str) -> None:
    print(a, b)


def bar(a: str, b: str = "") -> None:
    print(a, b)


@dataclass(frozen=True)
class Foobar:
    Foo: Callback
    Bar: Callback


config = Foobar(Foo=foo, Bar=bar)

Mypy在抱怨:

(function) foo: (a: str, b: str) -> None
Argument of type "(a: str, b: str) -> None" cannot be assigned to parameter "Foo" of type "Callback" in function "__init__"
  Type "(a: str, b: str) -> None" cannot be assigned to type "(a: str, b: str = "") -> None"
    Parameter "b" is missing default argument PylancereportGeneralTypeIssues
Argument "Foo" to "Foobar" has incompatible type "Callable[[str, str], None]"; expected "Callback"mypy(error)

有没有办法使这项工作?搜索此特定错误,我什么都没有解决

I'm trying to set default values for a specific callback protocol (I'd like any callback of the Callback type to require passing in argument a but optionally pass in argument b). With the following code:

from typing import Protocol
from dataclasses import dataclass


class Callback(Protocol):
    def __call__(self, a: str, b: str = "") -> None:
        ...


def foo(a: str, b: str) -> None:
    print(a, b)


def bar(a: str, b: str = "") -> None:
    print(a, b)


@dataclass(frozen=True)
class Foobar:
    Foo: Callback
    Bar: Callback


config = Foobar(Foo=foo, Bar=bar)

mypy is complaining with:

(function) foo: (a: str, b: str) -> None
Argument of type "(a: str, b: str) -> None" cannot be assigned to parameter "Foo" of type "Callback" in function "__init__"
  Type "(a: str, b: str) -> None" cannot be assigned to type "(a: str, b: str = "") -> None"
    Parameter "b" is missing default argument PylancereportGeneralTypeIssues
Argument "Foo" to "Foobar" has incompatible type "Callable[[str, str], None]"; expected "Callback"mypy(error)

Is there a way to make this work? Searching up this particular error gives me nothing to work off of

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

冷默言语 2025-02-01 06:38:33

如果我有一个fb = foobar(...),我应该能够做fb.foo(“”),但是如果fb.foofoo,因此类型错误

if I have a fb = Foobar(...), I should be able to do fb.Foo(""), but that wouldn't work if fb.Foo is foo, hence the type error

红颜悴 2025-02-01 06:38:33

您在__ Init __中定义了“ B”的类型,因此在下面重新定义它存在矛盾。

根据您的含义,我认为您可以将“ B”作为可选参数。

You defined the type of "b" in __init__, so there is a contradiction in redefining it below.

According to your meaning, I think you could make "b" an optional parameter.

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