Trouble using pinckle

  • Thread starter Pierre-Alain Dorange
  • Start date
P

Pierre-Alain Dorange

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():
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

def save(self):
f=open(kFileName,'w')
pickle.dump(self,f)
f.close()
return 0

def main():
p=Prefs()

p.load()
print 'test %d (after load)' % p.test
p.test+=1
print 'test %d (before save)' % p.test
p.save()
print '----------------------'

if __name__ == '__main__': main()
 
C

Cédric Lucantis

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)
 
P

Pierre-Alain Dorange

Cédric Lucantis said:
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).

Thanks, i was thinking about something like that.
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)

I try the staticmethod, it works fine. Very helpful.

But i don't like it very much, it seems 'complicated' (python was
supposed to be simple). I'll also try the dictionnary method.
My final idea was that a dictionnary would be perhaps simple in the
future to save/load as XML and a parser.

But perhaps i'm wrong with my vision of python.

On a more global perspective, what are the best method to implement a
simple config file with pyhton. Assuming i finally want to made a bundle
app for Mac, Windows and perhaps Linux.

I develop on Mac, and on this platform the config fil (preferences) have
to be stored in a special directory : ~/Library/Preferences, no problem.
But on other platform that's not the same directory and perhaps i would
also faced to permissions issues...
But first is there a way to determine on which platfrom the python
script is running ?
 
B

Bruno Desthuilliers

Pierre-Alain Dorange a écrit :
Thanks, i was thinking about something like that.
(snip)

I try the staticmethod, it works fine. Very helpful.

But i don't like it very much, it seems 'complicated' (python was
supposed to be simple).

Try doing the same thing in C++ !-)
I'll also try the dictionnary method.
My final idea was that a dictionnary would be perhaps simple in the
future to save/load as XML and a parser.

XML ? What a strange idea ?
But perhaps i'm wrong with my vision of python.
>
On a more global perspective, what are the best method to implement a
simple config file with pyhton.

Well... Python does have a couple of config-related packages, starting
with the one in the stdlib. You may want to find out if any of these
packages fits your needs before reinventing the wheel ?
Assuming i finally want to made a bundle
app for Mac, Windows and perhaps Linux.
I develop on Mac, and on this platform the config fil (preferences) have
to be stored in a special directory : ~/Library/Preferences, no problem.
But on other platform that's not the same directory and perhaps i would
also faced to permissions issues...

Yeps. Portability sometimes has a cost. I can't help you wrt/ Windows,
but on unix the convention is to save user's prefs in a .yourprogram
file (or directory) in the user's home directory.
But first is there a way to determine on which platfrom the python
script is running ?

the os package is your friend.
 
C

Cédric Lucantis

I'll also try the dictionnary method.
XML ? What a strange idea ?

Why is it so strange ? Many softs have their config in xml, and the xml.*
modules are not that hard to use. It makes sense if you have a lot of config
entries with nested sections.
Well... Python does have a couple of config-related packages, starting
with the one in the stdlib. You may want to find out if any of these
packages fits your needs before reinventing the wheel ?

Right, ConfigParser should do the trick for simpler things.
 
B

bruno.desthuilliers

Why is it so strange ?

It was kind of joke. But only kind of...
Many softs have their config in xml, and the xml.*
modules are not that hard to use. It makes sense if you have a lot of config
entries with nested sections.

Lightweight solutions like json or yaml comes to mind here...
 
P

Pierre-Alain Dorange

Bruno Desthuilliers said:
Try doing the same thing in C++ !-)

OK ;-)

I just ask myself what was the best method (according to python
phylosophy).
 
B

Bruno Desthuilliers

Pierre-Alain Dorange a écrit :
OK ;-)

I just ask myself what was the best method (according to python
phylosophy).

I'd personnaly use either one of the existing config packages, or
something like json or yaml.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top