Pickle a list

Irmen de Jong irmen at -NOSPAM-xs4all.nl
Tue Mar 8 18:17:57 EST 2011


On 07-03-11 17:38, Rogerio Luz wrote:
> 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)

                ^^^^^^^^^^^^^^^^^^^^^^
This probably doesn't do what you think it does.
It actually appends a range of numbers to the class attribute 'lista',
and not to the instance attribute of that name (which doesn't exist).

If you create multiple objects of type MyClass you'll notice that 
everytime the list gets longer and longer (...in *all* objects, because 
they still share the single class attribute!)

>          self.nome = "TestStr"
>          self.teste = 19900909
>

[...snip...]

The myClass object you're pickling doesn't have a 'lista' attribute.
While you can print myClass.lista without problems, you're printing the 
class attribute instead.
Pickle won't include class attributes. It just pickles the object's 
__dict__. If you add a line:     print(myClass.__dict__)
before the pickle() call you'll see that 'lista' is not in there. And 
that means that when you read the pickle back in, the new object won't 
have the 1,2,3,4,5.... numbers in the lista list, instead it just has 
the initial list.

You probably want to initialize self.alist in the class's __init__ 
method instead. That way it is a normal object attribute and will get 
pickled normally.


Irmen de Jong



More information about the Python-list mailing list