Mypy给出“不兼容的默认值”当dict param默认没有
我知道Python函数中的DICE参数最好设置为无默认值。但是,Mypy似乎不同意:
def example(self, mydict: Dict[int, str] = None):
return mydict.get(1)
这会导致Mypy错误:
error: Incompatible default for argument "synonyms" (default has type "None", argument has type "Dict[Any, Any]") [assignment]
另一方面,Mypy可以:
def example(self, myDict: Dict[int, str] = {}):
但是Pylint抱怨:
W0102: Dangerous default value {} as argument (dangerous-default-value)
根据这个问题( https://stackoverflow.com/a/26320917 ),默认值不应该是不适合Mypy的。什么可以满足皮层和mypy的选择?谢谢。
解决方案(基于评论):
class Example:
"""Example"""
def __init__(self):
self.d: Optional[Dict[int, str]] = None
def example(self, mydict: Optional[Dict[int, str]] = None):
"""example"""
self.d = mydict
问题的一部分(最初未提及)我将其分配回一个先前的变量,这项工作。
I understand that a Dict parameter in a Python function is best set to a default of None. However, mypy seems to disagree:
def example(self, mydict: Dict[int, str] = None):
return mydict.get(1)
This results in the mypy error:
error: Incompatible default for argument "synonyms" (default has type "None", argument has type "Dict[Any, Any]") [assignment]
mypy on the other hand is fine with this:
def example(self, myDict: Dict[int, str] = {}):
But pylint complains:
W0102: Dangerous default value {} as argument (dangerous-default-value)
According to this SO question (https://stackoverflow.com/a/26320917), the default should be None but that will not work with mypy. What is the option that will satisfy both pylint and mypy? Thanks.
SOLUTION (based on comments):
class Example:
"""Example"""
def __init__(self):
self.d: Optional[Dict[int, str]] = None
def example(self, mydict: Optional[Dict[int, str]] = None):
"""example"""
self.d = mydict
Part of the issue (not mentioned originally) I had was assigning back to a previously inited variable, this works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为该类型应为“
dict
或无
”,因此两个:union
of两者:I think the type should be "
dict
orNone
", so aUnion
of the two: