簡體   English   中英

Python 數據類:強制字典字段為深拷貝

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

我正在使用包含字典的數據類。

我希望 dict 成為一個深層副本,而不必依賴post_init調用,這基本上會使數據類失去興趣

什么是好的解決方案?

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

解決方案,如果不想使用__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