Revision 3 as of 2007-11-30 00:09:28

Clear message

extractor interface which can be used to extract C++ types from Python objects.

We have discussed two main use cases for extractions

1. In user code which needs to retrieve C++ objects from their corresponding Python objects:

  1. Getting value:
    •     void f(object x)
          {
              int y = extract<int>(x); // retrieve an int from x
          }
  2. Users may also want to explicitly check for convertibility:
    •     int g(object x)
          {
              extract<int> get_int(x);
              if (get_int.check())
                  return get_int();
              else
                  return 0;
          }

Example:

class A {
public:
  boost::python::list list;
  void listOperation(list& l);
};

Then you expose the class to python as:

class_<A>("A")
  .def_readwrite("b", &A::list)
  .def("op", &A::listOperation)
;

It is completely reasonable for python script to do something like this:

a = A()
a.b = [(1,2),(3,4),(5,6)]
a.op(a.b)

In order for you to extract the elements of tuples within the list, we use the index operator of the list:

void A::listOperation(list& l) {
   // Extract first element of first tuple in the list.
   extract<int>(extract<tuple>(list[0])())();
}

2. In the implementation of sequence from_python converters (e.g. Python tuple/list -> std::vector)

Unable to edit the page? See the FrontPage for instructions.