Pickling extension types
Peter Otten
__peter__ at web.de
Tue May 3 13:39:27 EDT 2011
Stefan Kuzminski wrote:
> I have an extension type written in C, but I cannot get it to pickle, any
> insights would be greatly appreciated.
>
> I see in the docs that I should define a __reduce__ method and that does
> get called, but I don't know specifically the type of the 'callable
> object' that should be the first thing in the tuple returned by
> __reduce__.
I haven't written a python extension in C, but I would approach the problem
by looking for prior art in the stdlib, preferably a simple class:
>>> 1j.__reduce__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle complex objects
OK, complex does something else... *
One grep through the source later:
>>> slice(1,2,3).__reduce__()
(<type 'slice'>, (1, 2, 3))
And the implementation seems straightforward:
static PyObject *
slice_reduce(PySliceObject* self)
{
return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop,
self->step);
}
(*) it uses __getnewargs__
More information about the Python-list
mailing list