Search code examples
pythonmypypylint

mypy gives "Incompatible default for argument" when Dict param defaults None


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.


Solution

  • 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)