设置默认参数的mypy call-arg错误
我的代码看起来如下:
from typing import Callable
def decorate(func: Callable[[str], None]) -> Callable[[str], None]:
return func
@decorate
def do_something(some_str: str = 'Hello world') -> None:
print(some_str)
if __name__ == '__main__':
do_something()
运行mypy时,它报告了最后一行的以下错误:
错误:“ do_something”的论点太少[call-arg]
如何修复此错误(而不将dectorate
的返回类型更改为callable [...,none]
)?
I have code that looks like the following:
from typing import Callable
def decorate(func: Callable[[str], None]) -> Callable[[str], None]:
return func
@decorate
def do_something(some_str: str = 'Hello world') -> None:
print(some_str)
if __name__ == '__main__':
do_something()
When running mypy, it reports the following error for the last line:
error: Too few arguments for "do_something" [call-arg]
How can I fix this error (without changing the return type of decorate
to Callable[..., None]
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
typeVar
表示输入和返回类型是 2ORES ,并由callable
收到的定义。由于可呼叫
类型包括整个签名,因此类型的检查器也可以推论位置/可选/关键字参数。如果
装饰
只能与可能采用字符串的可可配合使用,请相应地调整BONDEND
。值得注意的是,服用
str
或使用默认值仍然满足callable [[str],none]
,因为它可以使用a <调用代码> str 参数。Use a
TypeVar
to indicate that the input and return type are equivalent and defined by theCallable
received. SinceCallable
types include the entire signature, this lets the type checker infer positional/optional/keyword arguments as well.If
decorate
can only work with callables that may take a string, adjust thebound
accordingly.Notably, a callable taking a
str
or using a default still satisfiesCallable[[str], None]
since it can be called with astr
argument.协议
和__呼叫__
在表达功能类型时,给出了很多(某种冗长的)功率,不确定如何令人满意地避免避免“ Hello World!”复制。
Protocol
and__call__
give a lot of (somewhat verbose) power when expressing function typesNot sure how to satisfyingly avoid the "Hello World!" duplication.