[Numpy-discussion] pickable ndarray subclass

Stefan van der Walt stefan@sun.ac...
Sun Apr 15 09:06:35 CDT 2007


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.

Regards
Stéfan
-------------- next part --------------
A non-text attachment was scrubbed...
Name: infoarray.py
Type: text/x-python
Size: 1545 bytes
Desc: not available
Url : http://projects.scipy.org/pipermail/numpy-discussion/attachments/20070415/ebf0a380/attachment.py 


More information about the Numpy-discussion mailing list