Python使用默认值用于回调协议参数
我正在尝试为特定的回调协议设置默认值(我希望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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我有一个
fb = foobar(...)
,我应该能够做fb.foo(“”)
,但是如果fb.foo
是foo
,因此类型错误if I have a
fb = Foobar(...)
, I should be able to dofb.Foo("")
, but that wouldn't work iffb.Foo
isfoo
, hence the type error您在
__ 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.