是否可以在Python中对搁置对象进行深度复制?当我尝试深度检查它时,我收到以下错误:
import shelve,copy
input = shelve.open("test.dict", writeback=True)
input.update({"key1": 1, "key2": 2})
newinput = copy.deepcopy(input)
>> object.__new__(DB) is not safe, use DB.__new__()
这是否意味着货架不可复制?
编辑:如果我更详细地解释我的问题可能会更好:我保留一个大字典作为搁置对象,我想保存整个搁架对象(=我迄今为止生成的所有键,val对)我继续在原始字典中添加新项目时的单独文件。
可能我可以先同步搁架并明确地复制磁盘上的搁置文件,但我不喜欢这种方法。
答案 0 :(得分:1)
不,我不认为它们是可复制的(除非你修补课程或转换成字典)。原因如下:
copy.copy()
和copy.deepcopy()
为不依赖于“标准”类型(__copy__()
的实例调用__deepcopy__()
和atomic
方法, list
,tuple
和instance methods
)。如果该类没有这些属性,则会回退到__reduce_ex__
和__reduce__
。 (请参阅来源中的copy.py
)
不幸的是,搁置对象Shelf
基于UserDict.DictMixin
,它没有定义copy()
(Shelf
也没有):
类DictMixin:
# Mixin defining all dictionary methods for classes that already have # a minimum dictionary interface including getitem, setitem, delitem, # and keys. Without knowledge of the subclass constructor, the mixin # does not define __init__() or copy(). In addition to the four base # methods, progressively more efficiency comes with defining # __contains__(), __iter__(), and iteritems().
向搁置模块错误跟踪器提交问题可能是个好主意。
答案 1 :(得分:0)
您可以通过dict(input)
和deepcopy
获得浅色副本。然后可能在新文件上创建另一个搁架并通过update
方法填充它。
newinput = shelve.open("newtest.dict")
newinput.update(copy.deepcopy(dict(input)))