【发布时间】:2018-04-18 13:56:10
【问题描述】:
我在我的应用程序周围的不同位置使用了 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。
有人知道解决这个问题的方法吗?也许覆盖复制库的有效类型?
【问题讨论】:
-
什么是 dotdict,它从何而来?当
__reduce__被访问时,你可以重写它来抛出一个AttributeError吗? -
请提供minimal reproducible example 并指向您正在使用的特定库。是github.com/vkuznet/DotDict吗?
-
如果可能的话,看看导致错误的代码会很好吗?
-
实现你自己的副本...遍历字典并返回一个新的
-
问题已根据 cmets 更新。你能举个例子吗@shahaf
标签: python python-3.x copy deep-copy