Pickle problem

Jerry Hill malaclypse2 at gmail.com
Fri Apr 18 13:18:08 EDT 2008


On Fri, Apr 18, 2008 at 11:55 AM, Mario Ceresa <ceres83 at gmail.com> wrote:
> Hello everybody:
>  I'd like to use the pickle module to save the state of an object so to
>  be able to restore it later. The problem is that it holds a list of
>  other objects, say numbers, and if I modify the list and restore the
>  object, the list itself is not reverted to the saved one, but stays
>  with one element deleted.
...
>  -----------------------
>  class A(object):
>         objects = []
>  -----------------------

Your problem is in the class definition of A.  You declare objects as
a class variable, so it is shared between every instance of the class.
 When you pickle the instance a, then restore it, it continues to
reference the same list, which is help by the class.

You probably want the objects list to be an instance variable, like this:

class A(object):
    def __init__(self):
        self.objects = []

If you make that change, pickling and unpickling works the way you expect.

-- 
Jerry



More information about the Python-list mailing list