[Tutor] question concerning deepcopy

Gregor Lingl glingl at aon.at
Sat Apr 29 11:04:31 CEST 2006

Kent Johnson schrieb:
> Gregor Lingl wrote:
>>Hi all of you,
>>> from copy import deepcopy
>> >>> class Vec(tuple):
>>	def __new__(cls, x, y):
>>		return tuple.__new__(cls, (x,y))
>>	def __abs__(self):
>>		return (self[0]**2+self[1]**2)**0.5
>>         ## more methods ...
>> >>> a=Vec(3,4)
>> >>> abs(a)
>> >>> b = deepcopy(a)
>>Traceback (most recent call last):
>>TypeError: __new__() takes exactly 3 arguments (2 given)
> Apparently you need to define __getnewargs__() for your class. This works:
>      def __getnewargs__(self):
>          return (self[0], self[1])
> __getnewargs__() is documented with the pickle module but it is used by 
> deepcopy() as well.
> http://docs.python.org/lib/pickle-inst.html

Thanks, Kent  for the hint. It works (of course).
Skimming through this part of the docs I discovered, that there is a 
special method __deepcopy__. So I also  tried using this, adding

	def __deepcopy__(self,visit):
		return self

to my Vec class, which also seems to work. (I think this not to
be harmful as Vecs should be, like tuples, immutable).
And, indeed, it also seems to work.

Do you think this is also a correct way? If so, do you see there any 
advantages of one solution over the other one?


More information about the Tutor mailing list