2013-10-25 32 views
0

是否可以在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對)到一個單獨的文件,而我不斷添加新的項目,以原始字典。

也許我可以先同步擱置並明確地將擱置文件複製到磁盤上,但我不喜歡這種方法。

回答

0

您可以通過dict(input)deepcopy獲得淺拷貝。然後,可以在新文件上創建另一個擱架,並通過update方法填充它。

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

謝謝,它工作正常! – user2779485

1

不,我不認爲它們是可複製的(除非你將猴子補丁或轉換爲字典)。這裏的原因:

copy.copy()copy.deepcopy()呼叫__copy__()__deepcopy__()方法不依賴於「標準」型(這是atomiclisttupleinstance methods)的實例。如果班級沒有這些屬性,它將回落到__reduce_ex____reduce__。 (請參閱您的來源copy.py

不幸的是,貨架對象Shelf基於UserDict.DictMixin其中沒有定義copy()(而且也不Shelf):

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

可能提出的問題是個好主意到擱置模塊錯誤跟蹤器。

+0

我想知道如何檢查對象是否可複製,謝謝你的好解釋! – user2779485