Pickling an instance of a class containing a dict doesn't work

Jon Clements joncle at googlemail.com
Thu Oct 12 10:11:40 EDT 2006


Marco Lierfeld wrote:

> The class looks like this:
>         class subproject:
>                 configuration   = {}
>                 build_steps     = []
>                 # some functions
>                 # ...
>
> Now I create an instance of this class, e.g.
>         test = subproject()
> and try to save it with pickle.dump(test, file('test.pickle','wb')) or with
> pickle.Pickler(file('test.pickle','wb')).save(test) it looks like
> everything has worked well, but in the saved file 'test.pickle' only the
> list 'build_steps' is saved - the dictionary 'configuration' is missing.
> There is wether an error-message nor an exception.
>
> When I try to save only the dictionary, there is no problem at all - the
> dict is saved to the file.
>
> I also tried the 3 different protocols (0, 1, 2), but none of them worked
> for me.

At a wild guess. Since pickle descends the objects hierarchy, and since
configuration and build_steps aren't local to an instance of a class,
it stores only a reference to them (so you won't see values). However,
if you change the above to:

class subproject:
    def __init__(self):
        configuration = { }
        build_steps = [ ]

That'll probably be what you expect...

Jon.




More information about the Python-list mailing list