[Python-Dev] How to pickle class derived from c++ extension
Martin Drautzburg
Martin.Drautzburg at web.de
Fri Sep 14 22:48:15 CEST 2007
I understand that I can picke an extension class written in C/C++ by providing
a __reduce__() method along with __getstate__()/__setstate__(). While I still
havent gotten this to work, my main question is:
How could I possibly pickle an object of a python class which is derived from
the C++ extension?
It seems that I can define
>>> class Bar(list):
... pass
and add more attributes
>>> l=Bar()
>>> l.x=11
and __reduce__() will show the "x" attribute
>>> l.__reduce__()
(<function _reconstructor at 0xb7e2cf0c>, (<class '__main__.Bar'>,
<type 'list'>, []), {'x': 11})
But this does not seem to work with my extension class Foo. I defined a
__getstate__() method and __reduce__() indeed shows me some state. But if I
create a derived class Bar on the Python side and an object bar as an
instance of that class, and add an "x" attribute to that bar object, then
__reduce__ing that object shows nothing about the "x" attribute.
This is in a way undestandable, as __reduce__() eventually just calls
__getstate__() and the only implementation it can find is in my Foo extension
class, which knows nothing abpout the Bar derived class let alone its "x"
attribute.
I would like to have __reduce__() do it the pyhon way as far as it cat get,
and then call some magic method of my C++ class to pickle the "C++ part" of
an object. Is there a way to achieve this? The "list" class seems to have
something that my Foo class does not have. What is this?
Or of course if there is a better way, to picke objects of classes which are
derived from C++ extensions I'd be happy to hear about it.
More information about the Python-Dev
mailing list