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

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Jan 5 16:16:26 CET 2007

At Friday 5/1/2007 11:01, Emin wrote:

>Thank you for your reply. As you guessed, I want to be able to select
>the method at runtime as in your final example, but when I tried your
>suggestion I got the same error (see below). I think the problem is
>that getattr is donig something different than in my example where I
>explicitly get it from the dict (see the very end of the transcript

I've modified it as follows:
- using new.instancemethod to create the dynamic method
- copy uses __getstate__ to determine what is needed to copy/save. 
Assuming that self.x is derived from other attributes, it's not 
actually needed in the saved state, and can be omited.
- __setstate__ does the inverse: after reconstructing the object 
state, sets self.x to the right value

=== cut ===
import new

class A:
     def foo(self, arg):
         print "in foo, self=%r arg=%r" % (self, arg)

class B(A):
     def __init__(self):

     def update_dynamic_methods(self):
         "Should assign the dynamic methods based on other attributes"
         self.x = new.instancemethod(getattr(A,"foo"),self,B)

     def __getstate__(self):
         state = self.__dict__.copy()
         if 'x' in state: del state['x']
         return state

     def __setstate__(self, state):

b.something = 'something'

import copy
b2 = copy.deepcopy(b)
assert b2.something=='something'
=== cut ===

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