Pickle a list

Chris Kaynor ckaynor at zindagigames.com
Mon Mar 7 11:51:41 EST 2011


On Mon, Mar 7, 2011 at 8:38 AM, Rogerio Luz <rogeriosantosluz at gmail.com>wrote:

> Hi All
>
> I'd like to pickle an object instance with all values. So I
> instanciate myClass and set some values including a list with more
> values (in the __init__), then dump to file. I realized that the
> pickled object don't saved my new list values (saved only the
> "default" value) but saved a String and an int. What I'm doing wrong?
> Thanks Rogerio
>
> $ python3 pickler.py P
> Dump: ['default', 1, 2, 3, 4, 5, 6, 7, 8, 9] TestStr 19900909
>
> $ python3 pickler.py U
> Load: ['default'] TestStr 19900909
>
> # pickler.py
>
> import sys
> import pickle
>
> class MyClass:
>    teste = 0
>    nome = None
>    lista = ["default"]
>
>    def __init__(self):
>        for reg in range(1,10):
>            self.lista.append(reg)
>        self.nome = "TestStr"
>        self.teste = 19900909
>

In this definition, you are creating a class variable then appending your
arguments to it. Pickling won't save class variables - only
instance variables. The string and int work as you are reassigning them
within the __init__ function, thereby making them instance variables.

Something like:

class MyClass:
   teste = 0
   nome = None

   def __init__(self):
       self.lista = ['default']
       for reg in range(1,10):
           self.lista.append(reg)
       self.nome = "TestStr"
       self.teste = 19900909



> #main
> def main(argv):
>    if argv[1] == "P":
>        with open('myClass.pickle', 'wb') as f:
>            myClass = MyClass()
>            print("Dump:",myClass.lista, myClass.nome, myClass.teste)
>            pickle.dump(myClass, f, pickle.HIGHEST_PROTOCOL)
>
>    elif argv[1] == "U":
>        with open('myClass.pickle', 'rb') as f:
>            myClass = pickle.load(f)
>            print("Load:",myClass.lista, myClass.nome, myClass.teste)
>
> if __name__ == "__main__":
>    main(sys.argv)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110307/f58c2a4c/attachment.html>


More information about the Python-list mailing list