[Python-Dev] How to pickle class derived from c++ extension (original) (raw)

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