Python Pickle

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Apr 12 17:37:02 CEST 2010

gerardob a écrit :
> I have a problem using Pickle inside a class object.
> The following code works:
> m2 = markov_model.MarkovModel()
> m2 =  pickle.load(open("prueba", 'rb'))

Given the second line, the first is totally useless.

> print m2.n
> However, if I create the following method inside markov_model.MarkovModel: 
> def load_model_from_file(self, name):
> 	try:
> 		file = open(name, 'rb')			
> 		self = pickle.load(file)	

This doesn't work - or, more exactly, this doesn't work the way you 
expect it to work !-)

Remember that there's nothing magical with 'self' - it's just a local 
name in a function. Rebinding it within the function's body only affects 
the function's local namespace.

What you want is to make load_model_from_file a classmethod and make it 
return the unpickled object instead.

> 		file.close()
> 	except pickle.PicklingError: 
> 		print "PicklingError"

Useless exception handling - you lose all the relevant informations.

> and then run:
> m2 = markov_model.MarkovModel()
> m2.load_model_from_file("prueba")
> print m2.n
> it says that 'MarkovModel' object has no attribute 'n'. If the printing of
> 'n' i put it inside (at the end) of the method load_model_from_file as
> 'print self.n' it works.

Indeed - at this stage, the *local* 'self' name has been rebound to the 
unpickled object.

Also and fwiw, if you expect a MarkovModel instance to have a 'n' 
attribute, you should bind it (at least to a sensible default value) in 
the class __init__ method.

> How can i solve this?

cf above.


More information about the Python-list mailing list