[Numpy-discussion] pickable ndarray subclass

Christian K ckkart@hoc....
Tue Apr 17 01:06:18 CDT 2007


Stefan van der Walt wrote:
> Hi Christiaan
> 
> On Sun, Apr 15, 2007 at 02:03:49PM +0900, Christian K wrote:
>> could someone please provide example code for how to make a subclassed ndarray
>> pickable? I don't quite understand the docs of ndarray.__reduce__.
>> My subclassed ndarray has just one additional attribute.
>>
> 
> __reduce__ is part of the pickle protocol, which is described at
> 
> http://docs.python.org/lib/node321.html
> 
> You need to modify __reduce__ to store the complete state of your
> custom object, as well as __setstate__ which restores the state on
> unpickling.
> 
> See the attached code as an example.  There, I have an InfoArray,
> which is a subclassed numpy.ndarray.  The InfoArray contains an
> additional member, info, which is a dictionary.
> 
> The __reduce__ method calls ndarray's __reduce__, then adds to the
> result the state of the InfoArray.  Conversely, the __setstate__
> method calls ndarray's __setstate__ as well as restoring the info
> member.

Thank you for the explanation and the example. Works very well.

Christian



More information about the Numpy-discussion mailing list