bug in copy.deepcopy or in getattr or in my understanding?

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Jan 5 04:08:59 CET 2007

At Thursday 4/1/2007 17:26, Emin wrote:

>I got some unexpected behavior in getattr and copy.deepcopy (see
>transcript below). I'm not sure if this is actually a bug in
>copy.deepcopy or if I'm doing something too magical with getattr.
>Comments would be appreciated.

Both examples are different. #1 stores a *bound* method into an 
instance attribute. Bound methods carry a reference to "self", this 
creates a cyclic reference that may cause problems to the garbage 
collector (and confuses deepcopy, apparently).
#2 uses and *unbound* method and it's the usual way.

> >>> class a:
>...     def foo(self):
>...             print 'hi'
> >>> class b(a): #1
>...     def __init__(self):
>...             self.y = getattr(self,'foo')
> >>> class b(a): #2
>...     def __init__(self):
>...             self.x = self.__class__.__bases__[0].__dict__['foo']

For #2 you can simply say:

class b(a):
     x = a.foo

If you have to choose at runtime (a simplified version of your own code):

class b(a):
     def __init__(self):
         name = select_method_to_use(..., default="foo")
         self.x = getattr(a, name)

You *know* your bases because you wrote them in the class statement 
(or use super() instead of playing with __bases__); and getattr works 
fine here so you don't need to mess with the __dict__ details.

(Note that #1 was *almost* right, you had to replace self by the base class)

Gabriel Genellina
Softlab SRL 


Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 

More information about the Python-list mailing list