# Chapter 5. To/From Python Type Conversion

## boost/python/extract.hpp

### Introduction

Exposes a mechanism for extracting C++ object values from generalized Python objects. Note that `extract<...>` can also be used to "downcast" an `object` to some specific ObjectWrapper. Because invoking a mutable python type with an argument of the same type (e.g. `list([1,2]`) typically makes a copy of the argument object, this may be the only way to access the ObjectWrapper's interface on the original object.

### Class template `extract`

`extract<T>` can be used to extract a value of an arbitrary C++ type from an instance of object. Two usages are supported:

1. `extract<T>(o)` is a temporary object which is implicitly convertible to `T` (explicit conversion is also available through the object's function-call operator). However, if no conversion is available which can convert o to an object of type `T`, a Python TypeError exception will be raised.
2. `extract<T> x(o);` constructs an extractor whose `check()` member function can be used to ask whether a conversion is available without causing an exception to be thrown.

    namespace boost { namespace python
    {
      template <class T>
      struct extract
      {
          typedef unspecified result_type;

          extract(PyObject*);
          extract(object const&);

          result_type operator()() const;
          operator result_type() const;

          bool check() const;
      };
    }}

### Class template `extract` constructors and destructor

    extract(PyObject* p);
    extract(object const&);

Requires

  The first form requires that p is non-null.

Effects

  Stores a pointer to the Python object managed by its constructor argument. In particular, the reference count of the object is not incremented. The onus is on the user to be sure it is not destroyed before the extractor's conversion function is called.

### Class template `extract` observer functions

    result_type operator()() const;
    operator result_type() const;

Effects

  Converts the stored pointer to result_type, which is either T or T const&.

Returns

  An object of result_type corresponding to the one referenced by the stored pointer.

Throws

  `error_already_set` and sets a `TypeError` if no such conversion is available. May also emit other unspecified exceptions thrown by the converter which is actually used.

    bool check() const;

Postconditions

  None. In particular, note that a return value of true does not preclude an exception being thrown from operator result_type() or operator()().

Returns

  false only if no conversion from the stored pointer to T is available.

### Example

    #include <cstdio>
    using namespace boost::python;
    int Print(str s)
    {
       // extract a C string from the Python string object
       char const* c_str = extract<char const*>(s);

       // Print it using printf
       std::printf("%s\n", c_str);

       // Get the Python string's length and convert it to an int
       return extract<int>(s.attr("__len__")())
    }

The following example shows how extract can be used along with `class_<...>` to create and access an instance of a wrapped C++ class.

    struct X
    {
       X(int x) : v(x) {}
       int value() { return v; }
     private:
       int v;
    };

    BOOST_PYTHON_MODULE(extract_ext)
    {
        object x_class(
           class_<X>("X", init<int>())
              .def("value", &X::value))
              ;

        // Instantiate an X object through the Python interface.
        // Its lifetime is now managed by x_obj.
        object x_obj = x_class(3);

        // Get a reference to the C++ object out of the Python object
        X& x = extract<X&>(x_obj);
        assert(x.value() == 3);
    }