4

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.

Scott
  • 53
  • 1
  • 5
  • Side note, if `mydict` is `None`, then `mydict.get(1)` will result in an type error. Maybe you want something like `return mydict.get(1) if mydict is not None else None`. Or given your read-only usage of `mydict`, you could tell pylint to ignore this warning in this function. – Dunes May 05 '22 at 17:29
  • btw solutions go in the answer boxes, not as an addendum to the question - that way people can upvote/downvote it – joel May 06 '22 at 10:06

1 Answers1

4

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)
ForceBru
  • 43,482
  • 10
  • 63
  • 98