[英]How to deepcopy shelve objects in Python
是否可以在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对)保存到单独的文件中同时我继续向原始字典添加新项目。
也许我可以先同步搁置并明确地将搁置文件复制到磁盘上,但是我不喜欢这种方法。
不,我不认为它们是可复制的(除非您用猴子修补类或将其转换为字典)。 原因如下:
copy.copy()
和copy.deepcopy()
调用不依赖于“标准”类型(即atomic
, list
, tuple
和instance methods
)的实例的__copy__()
和__deepcopy__()
方法。 如果该类不具有这些属性,则它退回到__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().
将问题提交到搁置的模块错误跟踪器可能是个好主意。
你可以得到一个浅拷贝通过dict(input)
和deepcopy
那个。 然后,也许在新文件上创建另一个货架,并通过update
方法填充它。
newinput = shelve.open("newtest.dict")
newinput.update(copy.deepcopy(dict(input)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.