| Derived Object types

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

- list
- dict
- tuple
- str
- long_
- enum

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 `object`s 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);

`

Copyright © 2002 David Abrahams
Copyright © 2002 Joel de Guzman
Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.