From: W. Trevor King Date: Mon, 30 Aug 2010 17:22:27 +0000 (-0400) Subject: Maintain Curve._hooke setting during copy and deepcopy. X-Git-Url: http://git.tremily.us/?p=hooke.git;a=commitdiff_plain;h=78e658614176dcca603f9a38323084a169943b26;ds=sidebyside Maintain Curve._hooke setting during copy and deepcopy. --- diff --git a/hooke/curve.py b/hooke/curve.py index 42fa807..bc8138a 100644 --- a/hooke/curve.py +++ b/hooke/curve.py @@ -20,6 +20,8 @@ storing force curves. """ +from copy_reg import dispatch_table +from copy import _reconstruct, _copy_dispatch import logging import os.path @@ -201,6 +203,7 @@ class Curve (object): arguments: curve: *id001 command: curve info + explicit_user_call: true name: path path: some/path @@ -228,6 +231,7 @@ class Curve (object): name: path path: some/path command: curve info + explicit_user_call: true """ def __init__(self, path, info=None): @@ -277,6 +281,75 @@ class Curve (object): if type(self.command_stack) == list: self.command_stack = CommandStack() + def __copy__(self): + """Set copy to preserve :attr:`_hooke`. + + :meth:`getstate` drops :attr:`_hooke` for :mod:`pickle` and + :mod:`yaml` output, but it should be preserved (but not + duplicated) during copies. + + >>> import copy + >>> class Hooke (object): + ... pass + >>> h = Hooke() + >>> c = Curve(None) + >>> c.set_hooke(h) + >>> c._hooke # doctest: +ELLIPSIS + + >>> c._hooke == h + True + >>> c2 = copy.copy(c) + >>> c2._hooke # doctest: +ELLIPSIS + + >>> c2._hooke == h + True + """ + copier = _copy_dispatch.get(type(self)) + if copier: + return copier(self) + reductor = dispatch_table.get(type(self)) + if reductor: + rv = reductor(self) + else: + # :class:`object` implements __reduce_ex__, see :pep:`307`. + rv = self.__reduce_ex__(2) + y = _reconstruct(self, rv, 0) + y.set_hooke(self._hooke) + return y + + def __deepcopy__(self, memo): + """Set deepcopy to preserve :attr:`_hooke`. + + :meth:`getstate` drops :attr:`_hooke` for :mod:`pickle` and + :mod:`yaml` output, but it should be preserved (but not + duplicated) during copies. + + >>> import copy + >>> class Hooke (object): + ... pass + >>> h = Hooke() + >>> c = Curve(None) + >>> c.set_hooke(h) + >>> c._hooke # doctest: +ELLIPSIS + + >>> c._hooke == h + True + >>> c2 = copy.deepcopy(c) + >>> c2._hooke # doctest: +ELLIPSIS + + >>> c2._hooke == h + True + """ + reductor = dispatch_table.get(type(self)) + if reductor: + rv = reductor(self) + else: + # :class:`object` implements __reduce_ex__, see :pep:`307`. + rv = self.__reduce_ex__(2) + y = _reconstruct(self, rv, 1, memo) + y.set_hooke(self._hooke) + return y + def set_hooke(self, hooke=None): if hooke != None: self._hooke = hooke