【问题标题】:How to deepcopy shelve objects in Python如何在 Python 中深度复制搁置对象
【发布时间】:2013-10-25 08:31:12
【问题描述】:

是否可以在 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__()

这是否意味着书架不可复制?

编辑:如果我更详细地阐述我的问题可能会更好:我将一个大字典作为搁置对象,我想保存整个搁置对象(=到目前为止我生成的所有键、值对)到一个单独的文件,而我不断向原始字典添加新项目。

也许我可以先同步搁置文件,然后明确地将搁置文件复制到磁盘上,但是我不喜欢这种方法。

【问题讨论】:

    标签: python copy deep-copy shelve


    【解决方案1】:

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

    copy.copy()copy.deepcopy() 调用 __copy__()__deepcopy__() 方法用于不依赖于“标准”类型的实例(它们是 atomiclisttuple 和 @987654328 @)。如果该类没有这些属性,它将回退到 __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().
    

    向搁置模块错误跟踪器提交问题可能是个好主意。

    【讨论】:

    • 我想知道如何检查对象是否可复制,感谢您的精彩解释!
    【解决方案2】:

    您可以通过dict(input)deepcopy 获得浅拷贝。然后也许在一个新文件上创建另一个搁置并通过update 方法填充它。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多