Copy with __slots__

Griebel, Peer Peer.Griebel at
Wed Sep 18 13:35:38 CEST 2002


I just discovered another problem. It seems that objects which are instances
of new style classes (derived from object) are not copied correctly. Here is
an example:

class C1(object):
    __slots__ = "s1";

class C2(C1):
    __slots__ = "s2";

class C3(C2):

o1 = C1()
o2 = C2()
o3 = C3()

print o1.__slots__	# prints s1
print o2.__slots__	# prints s2
print o3.__slots__	# prints s2

o1.s1 = 11
o2.s1 = 21
o2.s2 = 22
o3.a = 5

import copy
p2 = copy.copy(o2)
print p2.s2		# attribute s2 does not exist (has not been copied)

The last print statement fails with the an AttributeError. Since
o2.__slots__ does not know about the slots of the parent class (C1), it
would not be sufficient to simply copy all elements in o2.__slots__. All
parent classes had to be inspected also.

So how can o2 be copied efficiently?

connection reset by

Dr. Peer Griebel                     Tel: +49(0) 731 / 9 74 95-0
Dipl. Inform.                       Fax: +49(0) 731 / 9 74 95-20
Entire Software AG                 mailto:Peer.Griebel at
Pfarrer-Weiß-Weg 10 - 12
D-89077 Ulm                       

More information about the Python-list mailing list