简体   繁体   English

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

[英]How to deepcopy shelve objects in Python

Is it possible to deepcopy a shelve object in Python? 是否可以在Python中深度复制搁置的对象? When I try to deepcopy it, I get the following error: 当我尝试对其进行深度复制时,出现以下错误:

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__()

Does it mean shelves are not-copyable? 这是否意味着货架不可复制?

Edit: Maybe it might be better if I elaborate my problem more: I am keeping a large dictionary as a shelve object, and I want to save the whole shelve object (= all key, val pairs I generated so far) to a seperate file while I keep adding new items to the original dict. 编辑:如果我进一步详细说明问题,可能会更好:我将一个大型词典保留为搁置对象,并且我想将整个搁置对象(=我到目前为止生成的所有键,val对)保存到单独的文件中同时我继续向原始字典添加新项目。

Probably I could first sync the shelve and copy the shelve file on disk explicitly, however I don't like that approach. 也许我可以先同步搁置并明确地将搁置文件复制到磁盘上,但是我不喜欢这种方法。

No, I don't think they are copiable (unless you monkey patch the class or convert into a dict). 不,我不认为它们是可复制的(除非您用猴子修补类或将其转换为字典)。 Here's why : 原因如下:

copy.copy() and copy.deepcopy() call the __copy__() and __deepcopy__() methods for the instances which does not depend on a "standard" type (which are atomic , list , tuple and instance methods ). copy.copy()copy.deepcopy()调用不依赖于“标准”类型(即atomiclisttupleinstance methods )的实例的__copy__()__deepcopy__()方法。 If the class does not have those attributes, it falls back to __reduce_ex__ and __reduce__ . 如果该类不具有这些属性,则它退回到__reduce_ex____reduce__ (see copy.py in your sources) (请参见源代码中的copy.py

Unfortunately, the shelve object Shelf is based on UserDict.DictMixin which does not define copy() (and neither does Shelf ) : 不幸的是,搁架对象Shelf基于UserDict.DictMixin ,它没有定义copy()Shelf也没有定义):

class DictMixin: 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(). 

It may be a good idea to submit an issue to the shelve module bug tracker. 将问题提交到搁置的模块错误跟踪器可能是个好主意。

You could obtain a shallow copy by dict(input) and deepcopy that. 你可以得到一个浅拷贝通过dict(input)deepcopy那个。 Then maybe create another shelve on a new file and populate it via the update method. 然后,也许在新文件上创建另一个货架,并通过update方法填充它。

newinput = shelve.open("newtest.dict")
newinput.update(copy.deepcopy(dict(input)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM