简体   繁体   English

Python 数据类:强制字典字段为深拷贝

[英]Python dataclass: Forcing a dictionary field to be a deep copy

I am working with a dataclass that contains a dict.我正在使用包含字典的数据类。

I want the dict to be a deepcopy, without having to rely on a post_init call, which would basically void to interest of a dataclass我希望 dict 成为一个深层副本,而不必依赖post_init调用,这基本上会使数据类失去兴趣

What would be a nice solution?什么是好的解决方案?

from dataclasses import dataclass, field
from typing import Dict


@dataclass
class ClassWithDict:
    the_dict: Dict = field(default_factory=dict, kw_only=True)


toto = {"toto": "tata"}
the_class = ClassWithDict(the_dict=toto)

assert toto == the_class.the_dict
assert toto is not the_class.the_dict  # FALSE

Solution, if not wanting to use a __post__init__ using the object.setattr method to force a copy once the object is initialized, is to use a metaclass :解决方案,如果不想使用__post__init__使用object.setattr方法在初始化 object 后强制复制,则使用metaclass

import copy
from dataclasses import dataclass, field
from typing import Dict


class DataClassWithDeepCopyMeta(type):

    def __call__(cls, *args, **kwargs):
        args = copy.deepcopy(args)
        kwargs = copy.deepcopy(kwargs)
        return super().__call__(*args, **kwargs)


@dataclass
class ClassWithDict(metaclass=DataClassWithDeepCopyMeta):
    the_dict: Dict = field(default_factory=dict)


toto = {"toto": "tata"}
the_class = ClassWithDict(toto)

assert toto == the_class.the_dict
assert toto is not the_class.the_dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM