Pickle: several class instance objects in one file?

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Mar 27 09:41:47 EDT 2008


On Thu, 27 Mar 2008 12:28:25 +0000, Dominique.Holzwarth wrote:

> Lets say I have instances of class A and class B:
> 
> a = A()
> b = B()
> 
> Is it possible to pickle both of these instances to the same pkl-file or
> will that have any bad impact for unpickle (i.e. the instance are
> 'mixed' or 'destroyed')? Or should I rather use a seperate file for
> every class instance I want to pickle?

You can pickle a data structure, for example a tuple, that contains both
instances.

Or you can write one after the other into the pickle file.  Then you'll
have to retrieve them in two steps too.

> Another very basic question about pickling class instances:
> 
> To store the value of attributes of an instance is it enough for the
> pickling-algorithm to use the __dict__ or do I have to implement the
> _setstate_ and _getstate_ function? I didn't really get the meaning of
> those while reading the python user manual...

Usually `pickle` just works.  Those methods can be used if you want to
customize the process, for example if you don't want to pickle the entire
object but just parts of it.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list