我正在尝试创建一个 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
Run Code Online (Sandbox Code Playgroud)
如何确保该bar字段对于每个实例都是一个新的字典?PEP-526中的所有字典示例似乎都使用 ClassVar,但这与我想要的相反。
我可能会在此处使用带有默认工厂函数(或 attrs 中的等效函数)的数据类,但我目前需要支持 python 3.6.x 和 3.7.x,因此这会增加一些开销。
就其价值而言,我正在测试的 python 版本是 3.7.3