Blame external/pybind11/docs/classes.rst

Packit 534379
.. _classes:
Packit 534379
Packit 534379
Object-oriented code
Packit 534379
####################
Packit 534379
Packit 534379
Creating bindings for a custom type
Packit 534379
===================================
Packit 534379
Packit 534379
Let's now look at a more complex example where we'll create bindings for a
Packit 534379
custom C++ data structure named ``Pet``. Its definition is given below:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    struct Pet {
Packit 534379
        Pet(const std::string &name) : name(name) { }
Packit 534379
        void setName(const std::string &name_) { name = name_; }
Packit 534379
        const std::string &getName() const { return name; }
Packit 534379
Packit 534379
        std::string name;
Packit 534379
    };
Packit 534379
Packit 534379
The binding code for ``Pet`` looks as follows:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    #include <pybind11/pybind11.h>
Packit 534379
Packit 534379
    namespace py = pybind11;
Packit 534379
Packit 534379
    PYBIND11_MODULE(example, m) {
Packit 534379
        py::class_<Pet>(m, "Pet")
Packit 534379
            .def(py::init<const std::string &>())
Packit 534379
            .def("setName", &Pet::setName)
Packit 534379
            .def("getName", &Pet::getName);
Packit 534379
    }
Packit 534379
Packit 534379
:class:`class_` creates bindings for a C++ *class* or *struct*-style data
Packit 534379
structure. :func:`init` is a convenience function that takes the types of a
Packit 534379
constructor's parameters as template arguments and wraps the corresponding
Packit 534379
constructor (see the :ref:`custom_constructors` section for details). An
Packit 534379
interactive Python session demonstrating this example is shown below:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    % python
Packit 534379
    >>> import example
Packit 534379
    >>> p = example.Pet('Molly')
Packit 534379
    >>> print(p)
Packit 534379
    <example.Pet object at 0x10cd98060>
Packit 534379
    >>> p.getName()
Packit 534379
    u'Molly'
Packit 534379
    >>> p.setName('Charly')
Packit 534379
    >>> p.getName()
Packit 534379
    u'Charly'
Packit 534379
Packit 534379
.. seealso::
Packit 534379
Packit 534379
    Static member functions can be bound in the same way using
Packit 534379
    :func:`class_::def_static`.
Packit 534379
Packit 534379
Keyword and default arguments
Packit 534379
=============================
Packit 534379
It is possible to specify keyword and default arguments using the syntax
Packit 534379
discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
Packit 534379
and :ref:`default_args` for details.
Packit 534379
Packit 534379
Binding lambda functions
Packit 534379
========================
Packit 534379
Packit 534379
Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> print(p)
Packit 534379
    <example.Pet object at 0x10cd98060>
Packit 534379
Packit 534379
To address this, we could bind an utility function that returns a human-readable
Packit 534379
summary to the special method slot named ``__repr__``. Unfortunately, there is no
Packit 534379
suitable functionality in the ``Pet`` data structure, and it would be nice if
Packit 534379
we did not have to change it. This can easily be accomplished by binding a
Packit 534379
Lambda function instead:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
        py::class_<Pet>(m, "Pet")
Packit 534379
            .def(py::init<const std::string &>())
Packit 534379
            .def("setName", &Pet::setName)
Packit 534379
            .def("getName", &Pet::getName)
Packit 534379
            .def("__repr__",
Packit 534379
                [](const Pet &a) {
Packit 534379
                    return "<example.Pet named '" + a.name + "'>";
Packit 534379
                }
Packit 534379
            );
Packit 534379
Packit 534379
Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
Packit 534379
With the above change, the same Python code now produces the following output:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> print(p)
Packit 534379
    <example.Pet named 'Molly'>
Packit 534379
Packit 534379
.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
Packit 534379
Packit 534379
.. _properties:
Packit 534379
Packit 534379
Instance and static fields
Packit 534379
==========================
Packit 534379
Packit 534379
We can also directly expose the ``name`` field using the
Packit 534379
:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
Packit 534379
method also exists for ``const`` fields.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
        py::class_<Pet>(m, "Pet")
Packit 534379
            .def(py::init<const std::string &>())
Packit 534379
            .def_readwrite("name", &Pet::name)
Packit 534379
            // ... remainder ...
Packit 534379
Packit 534379
This makes it possible to write
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> p = example.Pet('Molly')
Packit 534379
    >>> p.name
Packit 534379
    u'Molly'
Packit 534379
    >>> p.name = 'Charly'
Packit 534379
    >>> p.name
Packit 534379
    u'Charly'
Packit 534379
Packit 534379
Now suppose that ``Pet::name`` was a private internal variable
Packit 534379
that can only be accessed via setters and getters.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    class Pet {
Packit 534379
    public:
Packit 534379
        Pet(const std::string &name) : name(name) { }
Packit 534379
        void setName(const std::string &name_) { name = name_; }
Packit 534379
        const std::string &getName() const { return name; }
Packit 534379
    private:
Packit 534379
        std::string name;
Packit 534379
    };
Packit 534379
Packit 534379
In this case, the method :func:`class_::def_property`
Packit 534379
(:func:`class_::def_property_readonly` for read-only data) can be used to
Packit 534379
provide a field-like interface within Python that will transparently call
Packit 534379
the setter and getter functions:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
        py::class_<Pet>(m, "Pet")
Packit 534379
            .def(py::init<const std::string &>())
Packit 534379
            .def_property("name", &Pet::getName, &Pet::setName)
Packit 534379
            // ... remainder ...
Packit 534379
Packit 534379
Write only properties can be defined by passing ``nullptr`` as the
Packit 534379
input for the read function.
Packit 534379
Packit 534379
.. seealso::
Packit 534379
Packit 534379
    Similar functions :func:`class_::def_readwrite_static`,
Packit 534379
    :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
Packit 534379
    and :func:`class_::def_property_readonly_static` are provided for binding
Packit 534379
    static variables and properties. Please also see the section on
Packit 534379
    :ref:`static_properties` in the advanced part of the documentation.
Packit 534379
Packit 534379
Dynamic attributes
Packit 534379
==================
Packit 534379
Packit 534379
Native Python classes can pick up new attributes dynamically:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> class Pet:
Packit 534379
    ...     name = 'Molly'
Packit 534379
    ...
Packit 534379
    >>> p = Pet()
Packit 534379
    >>> p.name = 'Charly'  # overwrite existing
Packit 534379
    >>> p.age = 2  # dynamically add a new attribute
Packit 534379
Packit 534379
By default, classes exported from C++ do not support this and the only writable
Packit 534379
attributes are the ones explicitly defined using :func:`class_::def_readwrite`
Packit 534379
or :func:`class_::def_property`.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::class_<Pet>(m, "Pet")
Packit 534379
        .def(py::init<>())
Packit 534379
        .def_readwrite("name", &Pet::name);
Packit 534379
Packit 534379
Trying to set any other attribute results in an error:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> p = example.Pet()
Packit 534379
    >>> p.name = 'Charly'  # OK, attribute defined in C++
Packit 534379
    >>> p.age = 2  # fail
Packit 534379
    AttributeError: 'Pet' object has no attribute 'age'
Packit 534379
Packit 534379
To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
Packit 534379
must be added to the :class:`py::class_` constructor:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::class_<Pet>(m, "Pet", py::dynamic_attr())
Packit 534379
        .def(py::init<>())
Packit 534379
        .def_readwrite("name", &Pet::name);
Packit 534379
Packit 534379
Now everything works as expected:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> p = example.Pet()
Packit 534379
    >>> p.name = 'Charly'  # OK, overwrite value in C++
Packit 534379
    >>> p.age = 2  # OK, dynamically add a new attribute
Packit 534379
    >>> p.__dict__  # just like a native Python class
Packit 534379
    {'age': 2}
Packit 534379
Packit 534379
Note that there is a small runtime cost for a class with dynamic attributes.
Packit 534379
Not only because of the addition of a ``__dict__``, but also because of more
Packit 534379
expensive garbage collection tracking which must be activated to resolve
Packit 534379
possible circular references. Native Python classes incur this same cost by
Packit 534379
default, so this is not anything to worry about. By default, pybind11 classes
Packit 534379
are more efficient than native Python classes. Enabling dynamic attributes
Packit 534379
just brings them on par.
Packit 534379
Packit 534379
.. _inheritance:
Packit 534379
Packit 534379
Inheritance and automatic downcasting
Packit 534379
=====================================
Packit 534379
Packit 534379
Suppose now that the example consists of two data structures with an
Packit 534379
inheritance relationship:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    struct Pet {
Packit 534379
        Pet(const std::string &name) : name(name) { }
Packit 534379
        std::string name;
Packit 534379
    };
Packit 534379
Packit 534379
    struct Dog : Pet {
Packit 534379
        Dog(const std::string &name) : Pet(name) { }
Packit 534379
        std::string bark() const { return "woof!"; }
Packit 534379
    };
Packit 534379
Packit 534379
There are two different ways of indicating a hierarchical relationship to
Packit 534379
pybind11: the first specifies the C++ base class as an extra template
Packit 534379
parameter of the :class:`class_`:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::class_<Pet>(m, "Pet")
Packit 534379
       .def(py::init<const std::string &>())
Packit 534379
       .def_readwrite("name", &Pet::name);
Packit 534379
Packit 534379
    // Method 1: template parameter:
Packit 534379
    py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
Packit 534379
        .def(py::init<const std::string &>())
Packit 534379
        .def("bark", &Dog::bark);
Packit 534379
Packit 534379
Alternatively, we can also assign a name to the previously bound ``Pet``
Packit 534379
:class:`class_` object and reference it when binding the ``Dog`` class:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::class_<Pet> pet(m, "Pet");
Packit 534379
    pet.def(py::init<const std::string &>())
Packit 534379
       .def_readwrite("name", &Pet::name);
Packit 534379
Packit 534379
    // Method 2: pass parent class_ object:
Packit 534379
    py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
Packit 534379
        .def(py::init<const std::string &>())
Packit 534379
        .def("bark", &Dog::bark);
Packit 534379
Packit 534379
Functionality-wise, both approaches are equivalent. Afterwards, instances will
Packit 534379
expose fields and methods of both types:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> p = example.Dog('Molly')
Packit 534379
    >>> p.name
Packit 534379
    u'Molly'
Packit 534379
    >>> p.bark()
Packit 534379
    u'woof!'
Packit 534379
Packit 534379
The C++ classes defined above are regular non-polymorphic types with an
Packit 534379
inheritance relationship. This is reflected in Python:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // Return a base pointer to a derived instance
Packit 534379
    m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> p = example.pet_store()
Packit 534379
    >>> type(p)  # `Dog` instance behind `Pet` pointer
Packit 534379
    Pet          # no pointer downcasting for regular non-polymorphic types
Packit 534379
    >>> p.bark()
Packit 534379
    AttributeError: 'Pet' object has no attribute 'bark'
Packit 534379
Packit 534379
The function returned a ``Dog`` instance, but because it's a non-polymorphic
Packit 534379
type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
Packit 534379
considered polymorphic if it has at least one virtual function and pybind11
Packit 534379
will automatically recognize this:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    struct PolymorphicPet {
Packit 534379
        virtual ~PolymorphicPet() = default;
Packit 534379
    };
Packit 534379
Packit 534379
    struct PolymorphicDog : PolymorphicPet {
Packit 534379
        std::string bark() const { return "woof!"; }
Packit 534379
    };
Packit 534379
Packit 534379
    // Same binding code
Packit 534379
    py::class_<PolymorphicPet>(m, "PolymorphicPet");
Packit 534379
    py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
Packit 534379
        .def(py::init<>())
Packit 534379
        .def("bark", &PolymorphicDog::bark);
Packit 534379
Packit 534379
    // Again, return a base pointer to a derived instance
Packit 534379
    m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> p = example.pet_store2()
Packit 534379
    >>> type(p)
Packit 534379
    PolymorphicDog  # automatically downcast
Packit 534379
    >>> p.bark()
Packit 534379
    u'woof!'
Packit 534379
Packit 534379
Given a pointer to a polymorphic base, pybind11 performs automatic downcasting
Packit 534379
to the actual derived type. Note that this goes beyond the usual situation in
Packit 534379
C++: we don't just get access to the virtual functions of the base, we get the
Packit 534379
concrete derived type including functions and attributes that the base type may
Packit 534379
not even be aware of.
Packit 534379
Packit 534379
.. seealso::
Packit 534379
Packit 534379
    For more information about polymorphic behavior see :ref:`overriding_virtuals`.
Packit 534379
Packit 534379
Packit 534379
Overloaded methods
Packit 534379
==================
Packit 534379
Packit 534379
Sometimes there are several overloaded C++ methods with the same name taking
Packit 534379
different kinds of input arguments:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    struct Pet {
Packit 534379
        Pet(const std::string &name, int age) : name(name), age(age) { }
Packit 534379
Packit 534379
        void set(int age_) { age = age_; }
Packit 534379
        void set(const std::string &name_) { name = name_; }
Packit 534379
Packit 534379
        std::string name;
Packit 534379
        int age;
Packit 534379
    };
Packit 534379
Packit 534379
Attempting to bind ``Pet::set`` will cause an error since the compiler does not
Packit 534379
know which method the user intended to select. We can disambiguate by casting
Packit 534379
them to function pointers. Binding multiple functions to the same Python name
Packit 534379
automatically creates a chain of function overloads that will be tried in
Packit 534379
sequence.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::class_<Pet>(m, "Pet")
Packit 534379
       .def(py::init<const std::string &, int>())
Packit 534379
       .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
Packit 534379
       .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
Packit 534379
Packit 534379
The overload signatures are also visible in the method's docstring:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> help(example.Pet)
Packit 534379
Packit 534379
    class Pet(__builtin__.object)
Packit 534379
     |  Methods defined here:
Packit 534379
     |
Packit 534379
     |  __init__(...)
Packit 534379
     |      Signature : (Pet, str, int) -> NoneType
Packit 534379
     |
Packit 534379
     |  set(...)
Packit 534379
     |      1. Signature : (Pet, int) -> NoneType
Packit 534379
     |
Packit 534379
     |      Set the pet's age
Packit 534379
     |
Packit 534379
     |      2. Signature : (Pet, str) -> NoneType
Packit 534379
     |
Packit 534379
     |      Set the pet's name
Packit 534379
Packit 534379
If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
Packit 534379
syntax to cast the overloaded function:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::class_<Pet>(m, "Pet")
Packit 534379
        .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
Packit 534379
        .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
Packit 534379
Packit 534379
Here, ``py::overload_cast`` only requires the parameter types to be specified.
Packit 534379
The return type and class are deduced. This avoids the additional noise of
Packit 534379
``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
Packit 534379
on constness, the ``py::const_`` tag should be used:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    struct Widget {
Packit 534379
        int foo(int x, float y);
Packit 534379
        int foo(int x, float y) const;
Packit 534379
    };
Packit 534379
Packit 534379
    py::class_<Widget>(m, "Widget")
Packit 534379
       .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
Packit 534379
       .def("foo_const",   py::overload_cast<int, float>(&Widget::foo, py::const_));
Packit 534379
Packit 534379
If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only,
Packit 534379
you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    template <typename... Args>
Packit 534379
    using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
Packit 534379
Packit 534379
    py::class_<Pet>(m, "Pet")
Packit 534379
        .def("set", overload_cast_<int>()(&Pet::set), "Set the pet's age")
Packit 534379
        .def("set", overload_cast_<const std::string &>()(&Pet::set), "Set the pet's name");
Packit 534379
Packit 534379
.. [#cpp14] A compiler which supports the ``-std=c++14`` flag
Packit 534379
            or Visual Studio 2015 Update 2 and newer.
Packit 534379
Packit 534379
.. note::
Packit 534379
Packit 534379
    To define multiple overloaded constructors, simply declare one after the
Packit 534379
    other using the ``.def(py::init<...>())`` syntax. The existing machinery
Packit 534379
    for specifying keyword and default arguments also works.
Packit 534379
Packit 534379
Enumerations and internal types
Packit 534379
===============================
Packit 534379
Packit 534379
Let's now suppose that the example class contains an internal enumeration type,
Packit 534379
e.g.:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    struct Pet {
Packit 534379
        enum Kind {
Packit 534379
            Dog = 0,
Packit 534379
            Cat
Packit 534379
        };
Packit 534379
Packit 534379
        Pet(const std::string &name, Kind type) : name(name), type(type) { }
Packit 534379
Packit 534379
        std::string name;
Packit 534379
        Kind type;
Packit 534379
    };
Packit 534379
Packit 534379
The binding code for this example looks as follows:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::class_<Pet> pet(m, "Pet");
Packit 534379
Packit 534379
    pet.def(py::init<const std::string &, Pet::Kind>())
Packit 534379
        .def_readwrite("name", &Pet::name)
Packit 534379
        .def_readwrite("type", &Pet::type);
Packit 534379
Packit 534379
    py::enum_<Pet::Kind>(pet, "Kind")
Packit 534379
        .value("Dog", Pet::Kind::Dog)
Packit 534379
        .value("Cat", Pet::Kind::Cat)
Packit 534379
        .export_values();
Packit 534379
Packit 534379
To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
Packit 534379
``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Packit 534379
constructor. The :func:`enum_::export_values` function exports the enum entries
Packit 534379
into the parent scope, which should be skipped for newer C++11-style strongly
Packit 534379
typed enums.
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> p = Pet('Lucy', Pet.Cat)
Packit 534379
    >>> p.type
Packit 534379
    Kind.Cat
Packit 534379
    >>> int(p.type)
Packit 534379
    1L
Packit 534379
Packit 534379
The entries defined by the enumeration type are exposed in the ``__members__`` property:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> Pet.Kind.__members__
Packit 534379
    {'Dog': Kind.Dog, 'Cat': Kind.Cat}
Packit 534379
Packit 534379
The ``name`` property returns the name of the enum value as a unicode string.
Packit 534379
Packit 534379
.. note::
Packit 534379
Packit 534379
    It is also possible to use ``str(enum)``, however these accomplish different
Packit 534379
    goals. The following shows how these two approaches differ.
Packit 534379
Packit 534379
    .. code-block:: pycon
Packit 534379
Packit 534379
        >>> p = Pet( "Lucy", Pet.Cat )
Packit 534379
        >>> pet_type = p.type
Packit 534379
        >>> pet_type
Packit 534379
        Pet.Cat
Packit 534379
        >>> str(pet_type)
Packit 534379
        'Pet.Cat'
Packit 534379
        >>> pet_type.name
Packit 534379
        'Cat'
Packit 534379
Packit 534379
.. note::
Packit 534379
Packit 534379
    When the special tag ``py::arithmetic()`` is specified to the ``enum_``
Packit 534379
    constructor, pybind11 creates an enumeration that also supports rudimentary
Packit 534379
    arithmetic and bit-level operations like comparisons, and, or, xor, negation,
Packit 534379
    etc.
Packit 534379
Packit 534379
    .. code-block:: cpp
Packit 534379
Packit 534379
        py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
Packit 534379
           ...
Packit 534379
Packit 534379
    By default, these are omitted to conserve space.