Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 639
chaostheory Avatar asked Dec 07 '19 00:12

chaostheory


1 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})
like image 90
p_wm Avatar answered Nov 08 '22 15:11

p_wm