Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of boost. Click here for the latest Boost documentation.
Derived Object types

Boost.Python comes with a set of derived object types corresponding to that of Python's:

These derived object types act like real Python types. For instance:

    str(1) ==> "1"

Wherever appropriate, a particular derived object has corresponding Python type's methods. For instance, dict has a keys() method:

    d.keys()

make_tuple is provided for declaring tuple literals. Example:

    make_tuple(123, 'D', "Hello, World", 0.0);

In C++, when Boost.Python objects are used as arguments to functions, subtype matching is required. For example, when a function f, as declared below, is wrapped, it will only accept instances of Python's str type and subtypes.

    void f(str name)
    {
        object n2 = name.attr("upper")();   // NAME = name.upper()
        str NAME = name.upper();            // better
        object msg = "%s is bigger than %s" % make_tuple(NAME,name);
    }

In finer detail:

    str NAME = name.upper();

Illustrates that we provide versions of the str type's methods as C++ member functions.

    object msg = "%s is bigger than %s" % make_tuple(NAME,name);

Demonstrates that you can write the C++ equivalent of "format" % x,y,z in Python, which is useful since there's no easy way to do that in std C++.

Beware the common pitfall of forgetting that the constructors of most of Python's mutable types make copies, just as in Python.

Python:

    >>> d = dict(x.__dict__)     ##copies x.__dict__
    >>> d['whatever']            ##modifies the copy

C++:

    dict d(x.attr("__dict__"));  ##copies x.__dict__
    d['whatever'] = 3;           ##modifies the copy

class_<T> as objects

Due to the dynamic nature of Boost.Python objects, any class_<T> may also be one of these types! The following code snippet wraps the class (type) object.

We can use this to create wrapped instances. Example:

    object vec345 = (
        class_<Vec2>("Vec2", init<double, double>())
            .def_readonly("length", &Point::length)
            .def_readonly("angle", &Point::angle)
        )(3.0, 4.0);

    assert(vec345.attr("length") == 5.0);