如何深度复制在Python中搁置对象

时间:2013-10-25 08:31:13

标签: python copy deep-copy shelve

是否可以在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对)我继续在原始字典中添加新项目时的单独文件。

可能我可以先同步搁架并明确地复制磁盘上的搁置文件,但我不喜欢这种方法。

2 个答案:

答案 0 :(得分:1)

不,我不认为它们是可复制的(除非你修补课程或转换成字典)。原因如下:

copy.copy()copy.deepcopy()为不依赖于“标准”类型(__copy__()的实例调用__deepcopy__()atomic方法, listtupleinstance 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)))