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?
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With