Trouble using pinckle

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pierre-Alain Dorange

    Trouble using pinckle

    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='b onjour'

    def load(self):
    if os.path.exists( kFileName):
    try:
    print 'test %d (before)' % self.test
    f=open(kFileNam e,'r')
    self=pickle.loa d(f)
    f.close()
    print 'test %d (after)' % self.test
    except IOError:
    return 1

    return 0

    def save(self):
    f=open(kFileNam e,'w')
    pickle.dump(sel f,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()


    --
    Pierre-Alain Dorange

    Vidéo, DV et QuickTime <http://www.garage-video.com/>
    Clarus, the DogCow <http://clarus.chez.tis cali.fr/>
  • =?iso-8859-1?q?C=E9dric_Lucantis?=

    #2
    Re: Trouble using pinckle

    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='b onjour'
    >
    def load(self):
    if os.path.exists( kFileName):
    try:
    print 'test %d (before)' % self.test
    f=open(kFileNam e,'r')
    self=pickle.loa d(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(sel f, f)

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

    and load it with "prefs = Prefs.load(file name)"

    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(sel f.values, f)

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

    --
    Cédric Lucantis

    Comment

    • Pierre-Alain Dorange

      #3
      Re: Trouble using pinckle

      Cédric Lucantis <omer@no-log.orgwrote:
      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(sel f, f)
      >
      @staticmethod
      def load (f) :
      return pickle.load(f)
      >
      and load it with "prefs = Prefs.load(file name)"
      >
      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(sel f.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 ?

      --
      Pierre-Alain Dorange

      Vidéo, DV et QuickTime <http://www.garage-video.com/>
      Clarus, the DogCow <http://clarus.chez.tis cali.fr/>

      Comment

      • Bruno Desthuilliers

        #4
        Re: Trouble using pinckle

        Pierre-Alain Dorange a écrit :
        Cédric Lucantis <omer@no-log.orgwrote:
        >
        >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.
        >
        (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.

        Comment

        • =?iso-8859-1?q?C=E9dric_Lucantis?=

          #5
          Re: Trouble using pinckle

          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 ?
          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.
          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 ?
          Right, ConfigParser should do the trick for simpler things.

          --
          Cédric Lucantis

          Comment

          • bruno.desthuilliers@gmail.com

            #6
            Re: Trouble using pinckle

            On 2 juil, 18:40, Cédric Lucantis <o...@no-log.orgwrote:
            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 ?
            >
            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...

            Comment

            • Pierre-Alain Dorange

              #7
              Re: Trouble using pinckle

              Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalidwr ote:
              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++ !-)
              OK ;-)

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

              --
              Pierre-Alain Dorange

              Vidéo, DV et QuickTime <http://www.garage-video.com/>
              Clarus, the DogCow <http://clarus.chez.tis cali.fr/>

              Comment

              • Bruno Desthuilliers

                #8
                Re: Trouble using pinckle

                Pierre-Alain Dorange a écrit :
                Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalidwr ote:
                >
                >>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++ !-)
                >
                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.

                Comment

                Working...