Python type hinted Dict syntax error mutable default is not allowed. Use 'default factory'

Question:

I’m not sure why the interpreter is complaining about this typed Dict. For both instantiations, I get a “Mutable default is not allowed. Used default factory” syntax error. I’m using python 3.7.3

from dataclasses import dataclass
from typing import Dict

@dataclass
class Test:
    foo: Dict[str, int] = {}
    bar: Dict[str, float] = {'blah': 2.0}

Figured it out. It’s the @dataclass annotation that’s causing the issue. Can someone tell me why?

Asked By: chaostheory

||

Answers:

Yup, it’s dataclass raising to avoid your accidentally giving the same dict to every Test object instantiated with the default.

You could tweak the above to provide a default factory (a function which creates a new dict each time the default is needed) with the following:

from dataclasses import dataclass, field
from typing import Dict

@dataclass
class Test:
    foo: Dict[str, int] = field(default_factory=dict)
    bar: Dict[str, float] = field(default_factory=lambda: {'blah': 2.0})
Answered By: p_wm
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.