I'm trying to make a NamedTuple where one field defaults to an empty dictionary. This mostly works, however the default value is shared between instances of the NamedTuple:
from typing import NamedTuple, Dict
class MyTuple(NamedTuple):
foo: int
bar: Dict[str, str] = {}
t1 = MyTuple(1, {})
t2 = MyTuple(2)
t3 = MyTuple(3)
t2.bar["test2"] = "t2"
t3.bar["test3"] = "t3"
print(t2) # MyTuple(foo=2, bar={'test2': 't2', 'test3': 't3'})
print(t3) # MyTuple(foo=3, bar={'test2': 't2', 'test3': 't3'})
assert "test3" not in t2.bar # raises
How can I make sure the bar
field is a new dict for each instance? All of the examples of dicts in PEP-526 seem to use ClassVar, but that's the opposite of what I want here.
I could potentially use a dataclass here with a default factory function (or the equivalent in attrs), but I currently need to support python 3.6.x and 3.7.x, so that would add some overhead.
For what it's worth, the version of python where I'm testing this is 3.7.3