Trouble using pinckle

Cédric Lucantis omer at no-log.org
Wed Jul 2 10:45:21 EDT 2008


Le Wednesday 02 July 2008 16:09:07 Pierre-Alain Dorange, vous avez écrit :
> Hello,
>
> I'm new to python and i'm deelopping a small game with pygame.
> I got lot of fun with python.
>
> Trying to implement a config file to save user score and config.
> Reading doc and some tutorial about file handling i read about pickle,
> and yes it's very easy to implement.
> But i thought i miss something with the roots of python.
>
> I implement a Prefs class to handle config data and add it a load and
> save method. It works but when reading self, it OK inside the load
> function but outside the pref instance return to it's previus state...
> I don't really understand.
>
> Here's the test code :
>
> #!/usr/bin/env python
>
> import os, pickle
>
> kFileName='test.ini'
>
> class Prefs():

note that using new-style classes is recommended today:

class Prefs (object) :

>     def __init__(self):
>         self.test=1
>         self.zorglub='bonjour'
>
>     def load(self):
>         if os.path.exists(kFileName):
>             try:
>                 print 'test %d (before)' % self.test
>                 f=open(kFileName,'r')
>                 self=pickle.load(f)
>                 f.close()
>                 print 'test %d (after)' % self.test
>             except IOError:
>                 return 1
>
>         return 0
>

Here self is only a local variable and its meaning is only a convention. So 
assigning it to a new value won't change the object itself (and is not a good 
idea as it may be confusing for the reader).

You should either use a static method which returns a new object:

class Prefs (object) :

	def save (self, f) :
		pickle.dump(self, f)

	@staticmethod
	def load (f) :
		return pickle.load(f)

and load it with "prefs = Prefs.load(filename)"

or store all the values in a dictionary and only pickle this object:

class Prefs (object) :

	def __init__ (self) :
		self.values = { 'test': 1, ... }

	def save (self, f) :
		pickle.dump(self.values, f)

	def load (self, f) :
		self.values = pickle.load(f)

-- 
Cédric Lucantis



More information about the Python-list mailing list