当 Dict 参数默认为 None 时,mypy 给出 "Incompatible default for argument"
mypy gives "Incompatible default for argument" when Dict param defaults None
我知道 Python 函数中的 Dict 参数最好设置为默认值 None。不过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)
根据这个 SO 问题 (),默认值应该是 None 但这不适用于 mypy。满足 pylint 和 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
我遇到的部分问题(最初未提及)是分配回之前初始化的变量,这有效。
我认为类型应该是“dict
或 None
”,所以两者中的 Union
:
def example(self, mydict: Union[Dict[int, str], None] = None):
return mydict.get(1)
我知道 Python 函数中的 Dict 参数最好设置为默认值 None。不过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)
根据这个 SO 问题 (),默认值应该是 None 但这不适用于 mypy。满足 pylint 和 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
我遇到的部分问题(最初未提及)是分配回之前初始化的变量,这有效。
我认为类型应该是“dict
或 None
”,所以两者中的 Union
:
def example(self, mydict: Union[Dict[int, str], None] = None):
return mydict.get(1)