6 Creating bindings for a custom type
7 ===================================
9 Let's now look at a more complex example where we'll create bindings for a
10 custom C++ data structure named ``Pet``. Its definition is given below:
15 Pet(const std::string &name) : name(name) { }
16 void setName(const std::string &name_) { name = name_; }
17 const std::string &getName() const { return name; }
22 The binding code for ``Pet`` looks as follows:
26 #include <pybind11/pybind11.h>
28 namespace py = pybind11;
30 PYBIND11_MODULE(example, m) {
31 py::class_<Pet>(m, "Pet")
32 .def(py::init<const std::string &>())
33 .def("setName", &Pet::setName)
34 .def("getName", &Pet::getName);
37 :class:`class_` creates bindings for a C++ *class* or *struct*-style data
38 structure. :func:`init` is a convenience function that takes the types of a
39 constructor's parameters as template arguments and wraps the corresponding
40 constructor (see the :ref:`custom_constructors` section for details). An
41 interactive Python session demonstrating this example is shown below:
47 >>> p = example.Pet('Molly')
49 <example.Pet object at 0x10cd98060>
52 >>> p.setName('Charly')
58 Static member functions can be bound in the same way using
59 :func:`class_::def_static`.
61 Keyword and default arguments
62 =============================
63 It is possible to specify keyword and default arguments using the syntax
64 discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
65 and :ref:`default_args` for details.
67 Binding lambda functions
68 ========================
70 Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
75 <example.Pet object at 0x10cd98060>
77 To address this, we could bind an utility function that returns a human-readable
78 summary to the special method slot named ``__repr__``. Unfortunately, there is no
79 suitable functionality in the ``Pet`` data structure, and it would be nice if
80 we did not have to change it. This can easily be accomplished by binding a
81 Lambda function instead:
85 py::class_<Pet>(m, "Pet")
86 .def(py::init<const std::string &>())
87 .def("setName", &Pet::setName)
88 .def("getName", &Pet::getName)
91 return "<example.Pet named '" + a.name + "'>";
95 Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
96 With the above change, the same Python code now produces the following output:
101 <example.Pet named 'Molly'>
103 .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
107 Instance and static fields
108 ==========================
110 We can also directly expose the ``name`` field using the
111 :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
112 method also exists for ``const`` fields.
116 py::class_<Pet>(m, "Pet")
117 .def(py::init<const std::string &>())
118 .def_readwrite("name", &Pet::name)
121 This makes it possible to write
123 .. code-block:: pycon
125 >>> p = example.Pet('Molly')
128 >>> p.name = 'Charly'
132 Now suppose that ``Pet::name`` was a private internal variable
133 that can only be accessed via setters and getters.
139 Pet(const std::string &name) : name(name) { }
140 void setName(const std::string &name_) { name = name_; }
141 const std::string &getName() const { return name; }
146 In this case, the method :func:`class_::def_property`
147 (:func:`class_::def_property_readonly` for read-only data) can be used to
148 provide a field-like interface within Python that will transparently call
149 the setter and getter functions:
153 py::class_<Pet>(m, "Pet")
154 .def(py::init<const std::string &>())
155 .def_property("name", &Pet::getName, &Pet::setName)
160 Similar functions :func:`class_::def_readwrite_static`,
161 :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
162 and :func:`class_::def_property_readonly_static` are provided for binding
163 static variables and properties. Please also see the section on
164 :ref:`static_properties` in the advanced part of the documentation.
169 Native Python classes can pick up new attributes dynamically:
171 .. code-block:: pycon
177 >>> p.name = 'Charly' # overwrite existing
178 >>> p.age = 2 # dynamically add a new attribute
180 By default, classes exported from C++ do not support this and the only writable
181 attributes are the ones explicitly defined using :func:`class_::def_readwrite`
182 or :func:`class_::def_property`.
186 py::class_<Pet>(m, "Pet")
188 .def_readwrite("name", &Pet::name);
190 Trying to set any other attribute results in an error:
192 .. code-block:: pycon
194 >>> p = example.Pet()
195 >>> p.name = 'Charly' # OK, attribute defined in C++
197 AttributeError: 'Pet' object has no attribute 'age'
199 To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
200 must be added to the :class:`py::class_` constructor:
204 py::class_<Pet>(m, "Pet", py::dynamic_attr())
206 .def_readwrite("name", &Pet::name);
208 Now everything works as expected:
210 .. code-block:: pycon
212 >>> p = example.Pet()
213 >>> p.name = 'Charly' # OK, overwrite value in C++
214 >>> p.age = 2 # OK, dynamically add a new attribute
215 >>> p.__dict__ # just like a native Python class
218 Note that there is a small runtime cost for a class with dynamic attributes.
219 Not only because of the addition of a ``__dict__``, but also because of more
220 expensive garbage collection tracking which must be activated to resolve
221 possible circular references. Native Python classes incur this same cost by
222 default, so this is not anything to worry about. By default, pybind11 classes
223 are more efficient than native Python classes. Enabling dynamic attributes
224 just brings them on par.
228 Inheritance and automatic upcasting
229 ===================================
231 Suppose now that the example consists of two data structures with an
232 inheritance relationship:
237 Pet(const std::string &name) : name(name) { }
242 Dog(const std::string &name) : Pet(name) { }
243 std::string bark() const { return "woof!"; }
246 There are two different ways of indicating a hierarchical relationship to
247 pybind11: the first specifies the C++ base class as an extra template
248 parameter of the :class:`class_`:
252 py::class_<Pet>(m, "Pet")
253 .def(py::init<const std::string &>())
254 .def_readwrite("name", &Pet::name);
256 // Method 1: template parameter:
257 py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
258 .def(py::init<const std::string &>())
259 .def("bark", &Dog::bark);
261 Alternatively, we can also assign a name to the previously bound ``Pet``
262 :class:`class_` object and reference it when binding the ``Dog`` class:
266 py::class_<Pet> pet(m, "Pet");
267 pet.def(py::init<const std::string &>())
268 .def_readwrite("name", &Pet::name);
270 // Method 2: pass parent class_ object:
271 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
272 .def(py::init<const std::string &>())
273 .def("bark", &Dog::bark);
275 Functionality-wise, both approaches are equivalent. Afterwards, instances will
276 expose fields and methods of both types:
278 .. code-block:: pycon
280 >>> p = example.Dog('Molly')
286 The C++ classes defined above are regular non-polymorphic types with an
287 inheritance relationship. This is reflected in Python:
291 // Return a base pointer to a derived instance
292 m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });
294 .. code-block:: pycon
296 >>> p = example.pet_store()
297 >>> type(p) # `Dog` instance behind `Pet` pointer
298 Pet # no pointer upcasting for regular non-polymorphic types
300 AttributeError: 'Pet' object has no attribute 'bark'
302 The function returned a ``Dog`` instance, but because it's a non-polymorphic
303 type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
304 considered polymorphic if it has at least one virtual function and pybind11
305 will automatically recognize this:
309 struct PolymorphicPet {
310 virtual ~PolymorphicPet() = default;
313 struct PolymorphicDog : PolymorphicPet {
314 std::string bark() const { return "woof!"; }
318 py::class_<PolymorphicPet>(m, "PolymorphicPet");
319 py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
321 .def("bark", &PolymorphicDog::bark);
323 // Again, return a base pointer to a derived instance
324 m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });
326 .. code-block:: pycon
328 >>> p = example.pet_store2()
330 PolymorphicDog # automatically upcast
334 Given a pointer to a polymorphic base, pybind11 performs automatic upcasting
335 to the actual derived type. Note that this goes beyond the usual situation in
336 C++: we don't just get access to the virtual functions of the base, we get the
337 concrete derived type including functions and attributes that the base type may
338 not even be aware of.
342 For more information about polymorphic behavior see :ref:`overriding_virtuals`.
348 Sometimes there are several overloaded C++ methods with the same name taking
349 different kinds of input arguments:
354 Pet(const std::string &name, int age) : name(name), age(age) { }
356 void set(int age_) { age = age_; }
357 void set(const std::string &name_) { name = name_; }
363 Attempting to bind ``Pet::set`` will cause an error since the compiler does not
364 know which method the user intended to select. We can disambiguate by casting
365 them to function pointers. Binding multiple functions to the same Python name
366 automatically creates a chain of function overloads that will be tried in
371 py::class_<Pet>(m, "Pet")
372 .def(py::init<const std::string &, int>())
373 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
374 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
376 The overload signatures are also visible in the method's docstring:
378 .. code-block:: pycon
380 >>> help(example.Pet)
382 class Pet(__builtin__.object)
383 | Methods defined here:
386 | Signature : (Pet, str, int) -> NoneType
389 | 1. Signature : (Pet, int) -> NoneType
393 | 2. Signature : (Pet, str) -> NoneType
397 If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
398 syntax to cast the overloaded function:
402 py::class_<Pet>(m, "Pet")
403 .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
404 .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
406 Here, ``py::overload_cast`` only requires the parameter types to be specified.
407 The return type and class are deduced. This avoids the additional noise of
408 ``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
409 on constness, the ``py::const_`` tag should be used:
414 int foo(int x, float y);
415 int foo(int x, float y) const;
418 py::class_<Widget>(m, "Widget")
419 .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
420 .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
423 .. [#cpp14] A compiler which supports the ``-std=c++14`` flag
424 or Visual Studio 2015 Update 2 and newer.
428 To define multiple overloaded constructors, simply declare one after the
429 other using the ``.def(py::init<...>())`` syntax. The existing machinery
430 for specifying keyword and default arguments also works.
432 Enumerations and internal types
433 ===============================
435 Let's now suppose that the example class contains an internal enumeration type,
446 Pet(const std::string &name, Kind type) : name(name), type(type) { }
452 The binding code for this example looks as follows:
456 py::class_<Pet> pet(m, "Pet");
458 pet.def(py::init<const std::string &, Pet::Kind>())
459 .def_readwrite("name", &Pet::name)
460 .def_readwrite("type", &Pet::type);
462 py::enum_<Pet::Kind>(pet, "Kind")
463 .value("Dog", Pet::Kind::Dog)
464 .value("Cat", Pet::Kind::Cat)
467 To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
468 ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
469 constructor. The :func:`enum_::export_values` function exports the enum entries
470 into the parent scope, which should be skipped for newer C++11-style strongly
473 .. code-block:: pycon
475 >>> p = Pet('Lucy', Pet.Cat)
481 The entries defined by the enumeration type are exposed in the ``__members__`` property:
483 .. code-block:: pycon
485 >>> Pet.Kind.__members__
486 {'Dog': Kind.Dog, 'Cat': Kind.Cat}
490 When the special tag ``py::arithmetic()`` is specified to the ``enum_``
491 constructor, pybind11 creates an enumeration that also supports rudimentary
492 arithmetic and bit-level operations like comparisons, and, or, xor, negation,
497 py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
500 By default, these are omitted to conserve space.