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

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Jan 5 10:16:26 EST 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
>below):

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):
         self.update_dynamic_methods()

     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):
         self.__dict__.update(state)
         self.update_dynamic_methods()

b=B()
b.something = 'something'
b.foo(123)
b.x(123)

import copy
b2 = copy.deepcopy(b)
assert b2.something=='something'
b2.foo(123)
b2.x(123)
=== 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! 
http://www.yahoo.com.ar/respuestas 




More information about the Python-list mailing list