I'm trying to create a simple deepcopy function that simply skipps some object attributes, but my prototype implementation below goes into infinite recursion. Is this the right way to proceed?
from copy import deepcopy class Foo(): def __init__(self): self.copied = 1 self.skipped = 2 def __deepcopy__(self, memo): obj = type(self)() for attr in dir(self): if attr in ['skipped']: continue attr_copy = deepcopy(getattr(self, attr), memo) setattr(obj, attr, attr_copy) pass return obj o1 = Foo() o2 = deepcopy(o1) (I'm aware in this simple case I can just use delattr on a new instance, but for more complex cases I would like to use the deepcopy functionality.)
obj = type(self)()your code won't work ifFooneeds some parameter for__init__()other thanself. You should examine the (python) source code of thecopymodule; it's in your python installationLibfolder.