[C++-sig] Extracting C++ objects of different types from a Python list

Christopher Woods chryswoods at gmail.com
Thu Jun 28 09:43:02 CEST 2007

  Hi Craig,

I've played with your example and I've got it to work by changing your
extract<BaseClass> and extract<BaseClass&> into extract<BaseClass*>
and extract<const BaseClass*>. In the first case (extract<BaseClass>)
you were extracting the object in the list into a *copy*, which was of
type BaseClass, so the "Useless base class" function of that copy was
then called. By extracting into a pointer (via extract<BaseClass*>)
you aren't performing a copy, and you obtain a polymorphic pointer to
the original object.

As for the typeid part of the example, I don't know why typeid gets it
wrong when you use extract<BaseClass&>. I had to change this to
extract<const BaseClass*> and then do a typeid of the dereference of
the resulting polymorphic pointer.

Here is the modified version of 'setList' that worked on my box
(linux, gcc 3.4, python 2.3);

void Importer::setList (list l) {
   BaseClass *o;
   int len = extract<int>(l.attr("__len__")());

   for (int i=0; i<len; i++) {
       std::cout << typeid( *(extract <const BaseClass*> (l[i]))
).name() << std::endl;

       o = extract <BaseClass*> (l[i]);

This gave output;

Index is 3
Value is 5.234

  I hope this helps,


More information about the Cplusplus-sig mailing list