[Tutor] question about __copy__ and __deepcopy__

Steven D'Aprano steve at pearwood.info
Fri Apr 15 02:30:16 EDT 2016


On Thu, Apr 14, 2016 at 07:38:31PM +0000, Albert-Jan Roskam wrote:
> Hi,
> 
> Lately I have been using the "mutable namedtuple"  shown below a lot. 
> I found it somewhere on StackOverflow or ActiveState or something. In 
> its original form, it only had an __init__ method. I noticed that 
> copying Record objects sometimes failed.

Failed how?

Given how simple the class looks, I wonder whether that's a bug in copy. 
Apart from a fancy __str__ method, there's practically nothing to it!

So I took your Record class, stripped out the __copy__ and __deepcopy__ 
methods, created a slightly complex instance, and tried copying it:

d = Record(spam=23, ham=42, eggs=[], cheese={})
d.cheese[1] = None
d.cheese[2] = ['a', 'b', 'c']
d.eggs.append(100)
d.eggs.append(200)
d.eggs.append(d)
d.eggs.append(d.cheese)

from copy import copy, deepcopy

copy(d)
deepcopy(d)


and both appeat to work correctly. So perhaps you ought to look more 
carefully at the copying failure?



-- 
Steve


More information about the Tutor mailing list