开发者

Implementing recursion with a deep copy

开发者 https://www.devze.com 2023-03-11 13:47 出处:网络
How can I implement recursion in a deep copy function object? This is the relevant code (if you want more then please ask):

How can I implement recursion in a deep copy function object? This is the relevant code (if you want more then please ask): PS: I would like the recursion to iterate throug开发者_运维问答h a filtered list of references. The goal is to download and insert any missing objects.

copy.py

from put import putter

class copier:
  def __init__(self, base):
    self.base = base
  def copyto(self, obj):
    put = putter(obj)
    for x in self.base.__dict__:
      put(x)

put.py

class putter:
  def __init__(self, parent):
    self.parent = parent
  def put(self, name, obj):
    self.parent.__dict__[name] = obj


Check out the documentation for copy.deepcopy, if you can implement what you want with __getinitargs__(), __getstate__() and __setstate__(), then that will save you a lot of grief. Otherwise, you will need to reimplement it yourself, it should look something like:

def deepcopyif(obj, shouldcopyprop):
    copied = {} # Remember what has already been copied
    def impl(obj):
        if obj in copied:
            return copied[obj]
        newobj = *** Create a copy ***
        copied[obj] = newobj # IMPORTANT: remember the new object before recursing
        for name, value in obj.__dict__: # or whatever...
            if shouldcopyprop(obj.__class__, name): # or whatever
                value = impl(value) # RECURSION: this will copy the property value
            newobj.__dict__[prop] = value
        return newobj
    return impl(obj)
0

精彩评论

暂无评论...
验证码 换一张
取 消