Skip to main content
 首页 » 编程设计

python之在 dotdict 上使用 copy.deepcopy

2025年05月04日21落叶

我在我的应用程序周围的不同位置使用了 dotdict 来增强我的代码的可读性。我几乎不知道这会导致很多问题。一个特别烦人的情况是它似乎与副本库不兼容。

这就是我所说的 dotdict

class DotDict(dict): 
    """dot.notation access to dictionary attributes""" 
    __getattr__ = dict.get 
    __setattr__ = dict.__setitem__ 
    __delattr__ = dict.__delitem__ 

即一种访问字典属性的方法:dictionary.attribute

当我尝试

nested_dico = DotDict({'example':{'nested':'dico'}}) 
copy.deepcopy(nested_dico) 

我收到以下错误:

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/copy.py in deepcopy(x, memo, _nil) 
    167                     reductor = getattr(x, "__reduce_ex__", None) 
    168                     if reductor: 
--> 169                         rv = reductor(4) 
    170                     else: 
    171                         reductor = getattr(x, "__reduce__", None) 
 
TypeError: 'NoneType' object is not callable 

我假设这是因为它不识别我的 DotDict 类,因此认为它是 NoneType。

有人知道解决这个问题的方法吗?也许覆盖复制库的有效类型?

请您参考如下方法:

查看错误发生的地方,reductor 不是None,而是一个内置函数,这意味着错误发生在 C 代码的某个地方,我们可以'看到回溯。但我的猜测是它试图获取一个它不确定是否存在的方法,如果不存在则准备捕获 AttributeError。相反,它会调用 .get,它会返回 None 而不会出现错误,因此它会尝试调用该方法。

这行为正确:

class DotDict(dict): 
    """dot.notation access to dictionary attributes""" 
 
    def __getattr__(self, item): 
        try: 
            return self[item] 
        except KeyError as e: 
            raise AttributeError from e 
 
    __setattr__ = dict.__setitem__ 
    __delattr__ = dict.__delitem__ 
 
a = DotDict(x=1, b=2) 
 
print(deepcopy(a)) 

我知道这与您的原始类的行为不同,您将无法使用 . 作为可选键,但我认为有必要使用外部代码避免此类错误期望您的类(class)以可预测的方式行事。

编辑:这是一种实现深度复制并保留原始 __getattr__ 的方法:

class DotDict(dict): 
    """dot.notation access to dictionary attributes""" 
 
    __getattr__ = dict.get 
    __setattr__ = dict.__setitem__ 
    __delattr__ = dict.__delitem__ 
 
    def __deepcopy__(self, memo=None): 
        return DotDict(deepcopy(dict(self), memo=memo)) 

测试:

dd = DotDict(x=1, b=2, nested=DotDict(y=3)) 
 
copied = deepcopy(dd) 
print(copied) 
assert copied == dd 
assert copied.nested == dd.nested 
assert copied.nested is not dd.nested 
assert type(dd) is type(copied) is type(dd.nested) is type(copied.nested) is DotDict