[Tutor] question concerning deepcopy

Kent Johnson kent37 at tds.net
Fri Apr 28 19:44:18 CEST 2006


Gregor Lingl wrote:
> Hi all of you,
> 
> I've some Vector class, which is a subclass of tuple and which is 
> working satisfactorily since long in different contexts. Now I've 
> constructed objects with attributes of Vec-type, which I wanted to 
> deepcopy. But that doesn't work, because I can't (deep)copy Vec-s:
> 
>  >>> 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)
> 5.0
>  >>> b = deepcopy(a)
> 
> Traceback (most recent call last):
>    File "<pyshell#13>", line 1, in -toplevel-
>      b = deepcopy(a)
>    File "C:\Python24\lib\copy.py", line 204, in deepcopy
>      y = _reconstruct(x, rv, 1, memo)
>    File "C:\Python24\lib\copy.py", line 336, in _reconstruct
>      y = callable(*args)
>    File "C:\Python24\lib\copy_reg.py", line 92, in __newobj__
>      return cls.__new__(cls, *args)
> 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

Kent



More information about the Tutor mailing list