Mypy给出“不兼容的默认值”当dict param默认没有

发布于 2025-01-26 10:58:40 字数 995 浏览 0 评论 0原文

我知道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 技术交流群。

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

发布评论

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

评论(1

后来的我们 2025-02-02 10:58:40

我认为该类型应为“ dict”,因此两个:union of两者:

def example(self, mydict: Union[Dict[int, str], None] = None):
        return mydict.get(1)

I think the type should be "dict or None", so a Union of the two:

def example(self, mydict: Union[Dict[int, str], None] = None):
        return mydict.get(1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文