Friday, 15 July 2011

python - How do you pass options to deepcopy? -



python - How do you pass options to deepcopy? -

in this question, anthony hatchkins gives default implementation of deepcopy based on dict-copying code python falls to:

def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result k, v in self.__dict__.items(): setattr(result, k, deepcopy(v, memo)) homecoming result

i default implementation based on pickling , unpickling, python chooses before falling dict-copying.

here attempt, did not work:

def __deepcopy__(self, memo): new, args, state = self.__reduce__() result = new(*args) if state: result.__setstate__(state) memo[id(self)] = result homecoming result

once have such method, can create version additional options copied , how copying done.

the existence of cut down , and setstate guaranteed base of operations class defines:

@staticmethod def kwargs_new(cls, new_kwargs, *new_args): """ override method utilize different new. """ retval = cls.__new__(cls, *new_args, **new_kwargs) retval.__init__(*new_args, **new_kwargs) homecoming retval """ define default getstate , setstate utilize in coöperative inheritance. """ def __getstate__(self): homecoming {} def __setstate__(self, state): self.__dict__.update(state) def __getnewargs_ex__(self): homecoming ((), {}) def __reduce__(self): """ reimplement __reduce__ calls __getnewargs_ex__ regardless of python version. pass keyword arguments object.__new__. exposes kwargs_new static method can overridden utilize __reduce__. """ new_args, new_kwargs = self.__getnewargs_ex__() state = self.__getstate__() homecoming (type(self).kwargs_new, (type(self), new_kwargs,) + tuple(new_args), state)

the state passed setstate needs copied argument list:

def __deepcopy__(self, memo): """ reimplement __deepcopy__ * supports keyword arguments reduce. """ kwargs = memo.get('deepcopy kwargs', {}) new, args, state = self.__reduce__(**kwargs) args_copy = copy.deepcopy(args, memo) result = new(*args_copy) memo[id(self)] = result if state: state_copy = copy.deepcopy(state, memo) result.__setstate__(state_copy) homecoming result

this version of deepcopy has been modified utilize special memo pass keyword arguments reduce.

python python-3.x pickle deep-copy

No comments:

Post a Comment