我想创建一个NamedTuple,在其中一个字段的默认值为一个空字典。这基本上是可行的,但是默认值在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
我该如何确保每个实例的
bar
字段都是一个新字典?在PEP-526中,所有字典的示例似乎都使用了ClassVar,但这与我想要的相反。
我可能可以在这里使用dataclass和默认工厂函数(或attrs中的等价物),但我目前需要支持python 3.6.x和3.7.x,所以这会增加一些开销。
值得一提的是,我测试这个的Python版本是3.7.3。