blob: 5843e24475d339868e67afa92ce9f8f351a9a24b [file] [log] [blame]
Dean Moldovan67b52d82016-10-16 19:12:43 +02001Classes
2#######
3
4This section presents advanced binding code for classes and it is assumed
5that you are already familiar with the basics from :doc:`/classes`.
6
7.. _overriding_virtuals:
8
9Overriding virtual functions in Python
10======================================
11
12Suppose that a C++ class or interface has a virtual function that we'd like to
13to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is
14given as a specific example of how one would do this with traditional C++
15code).
16
17.. code-block:: cpp
18
19 class Animal {
20 public:
21 virtual ~Animal() { }
22 virtual std::string go(int n_times) = 0;
23 };
24
25 class Dog : public Animal {
26 public:
27 std::string go(int n_times) override {
28 std::string result;
29 for (int i=0; i<n_times; ++i)
30 result += "woof! ";
31 return result;
32 }
33 };
34
35Let's also suppose that we are given a plain function which calls the
36function ``go()`` on an arbitrary ``Animal`` instance.
37
38.. code-block:: cpp
39
40 std::string call_go(Animal *animal) {
41 return animal->go(3);
42 }
43
44Normally, the binding code for these classes would look as follows:
45
46.. code-block:: cpp
47
48 PYBIND11_PLUGIN(example) {
49 py::module m("example", "pybind11 example plugin");
50
51 py::class_<Animal> animal(m, "Animal");
52 animal
53 .def("go", &Animal::go);
54
55 py::class_<Dog>(m, "Dog", animal)
56 .def(py::init<>());
57
58 m.def("call_go", &call_go);
59
60 return m.ptr();
61 }
62
63However, these bindings are impossible to extend: ``Animal`` is not
64constructible, and we clearly require some kind of "trampoline" that
65redirects virtual calls back to Python.
66
67Defining a new type of ``Animal`` from within Python is possible but requires a
68helper class that is defined as follows:
69
70.. code-block:: cpp
71
72 class PyAnimal : public Animal {
73 public:
74 /* Inherit the constructors */
75 using Animal::Animal;
76
77 /* Trampoline (need one for each virtual function) */
78 std::string go(int n_times) override {
79 PYBIND11_OVERLOAD_PURE(
80 std::string, /* Return type */
81 Animal, /* Parent class */
82 go, /* Name of function */
83 n_times /* Argument(s) */
84 );
85 }
86 };
87
88The macro :func:`PYBIND11_OVERLOAD_PURE` should be used for pure virtual
89functions, and :func:`PYBIND11_OVERLOAD` should be used for functions which have
90a default implementation. There are also two alternate macros
91:func:`PYBIND11_OVERLOAD_PURE_NAME` and :func:`PYBIND11_OVERLOAD_NAME` which
92take a string-valued name argument between the *Parent class* and *Name of the
93function* slots. This is useful when the C++ and Python versions of the
94function have different names, e.g. ``operator()`` vs ``__call__``.
95
96The binding code also needs a few minor adaptations (highlighted):
97
98.. code-block:: cpp
99 :emphasize-lines: 4,6,7
100
101 PYBIND11_PLUGIN(example) {
102 py::module m("example", "pybind11 example plugin");
103
104 py::class_<Animal, PyAnimal /* <--- trampoline*/> animal(m, "Animal");
105 animal
106 .def(py::init<>())
107 .def("go", &Animal::go);
108
109 py::class_<Dog>(m, "Dog", animal)
110 .def(py::init<>());
111
112 m.def("call_go", &call_go);
113
114 return m.ptr();
115 }
116
117Importantly, pybind11 is made aware of the trampoline helper class by
118specifying it as an extra template argument to :class:`class_`. (This can also
119be combined with other template arguments such as a custom holder type; the
120order of template types does not matter). Following this, we are able to
121define a constructor as usual.
122
123Note, however, that the above is sufficient for allowing python classes to
124extend ``Animal``, but not ``Dog``: see ref:`virtual_and_inheritance` for the
125necessary steps required to providing proper overload support for inherited
126classes.
127
128The Python session below shows how to override ``Animal::go`` and invoke it via
129a virtual method call.
130
131.. code-block:: pycon
132
133 >>> from example import *
134 >>> d = Dog()
135 >>> call_go(d)
136 u'woof! woof! woof! '
137 >>> class Cat(Animal):
138 ... def go(self, n_times):
139 ... return "meow! " * n_times
140 ...
141 >>> c = Cat()
142 >>> call_go(c)
143 u'meow! meow! meow! '
144
145Please take a look at the :ref:`macro_notes` before using this feature.
146
147.. note::
148
149 When the overridden type returns a reference or pointer to a type that
150 pybind11 converts from Python (for example, numeric values, std::string,
151 and other built-in value-converting types), there are some limitations to
152 be aware of:
153
154 - because in these cases there is no C++ variable to reference (the value
155 is stored in the referenced Python variable), pybind11 provides one in
156 the PYBIND11_OVERLOAD macros (when needed) with static storage duration.
157 Note that this means that invoking the overloaded method on *any*
158 instance will change the referenced value stored in *all* instances of
159 that type.
160
161 - Attempts to modify a non-const reference will not have the desired
162 effect: it will change only the static cache variable, but this change
163 will not propagate to underlying Python instance, and the change will be
164 replaced the next time the overload is invoked.
165
166.. seealso::
167
168 The file :file:`tests/test_virtual_functions.cpp` contains a complete
169 example that demonstrates how to override virtual functions using pybind11
170 in more detail.
171
172.. _virtual_and_inheritance:
173
174Combining virtual functions and inheritance
175===========================================
176
177When combining virtual methods with inheritance, you need to be sure to provide
178an override for each method for which you want to allow overrides from derived
179python classes. For example, suppose we extend the above ``Animal``/``Dog``
180example as follows:
181
182.. code-block:: cpp
183
184 class Animal {
185 public:
186 virtual std::string go(int n_times) = 0;
187 virtual std::string name() { return "unknown"; }
188 };
myd73499b815ad2017-01-13 18:15:52 +0800189 class Dog : public Animal {
Dean Moldovan67b52d82016-10-16 19:12:43 +0200190 public:
191 std::string go(int n_times) override {
192 std::string result;
193 for (int i=0; i<n_times; ++i)
194 result += bark() + " ";
195 return result;
196 }
197 virtual std::string bark() { return "woof!"; }
198 };
199
200then the trampoline class for ``Animal`` must, as described in the previous
201section, override ``go()`` and ``name()``, but in order to allow python code to
202inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
203overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
204methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
205override the ``name()`` method):
206
207.. code-block:: cpp
208
209 class PyAnimal : public Animal {
210 public:
211 using Animal::Animal; // Inherit constructors
212 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Animal, go, n_times); }
213 std::string name() override { PYBIND11_OVERLOAD(std::string, Animal, name, ); }
214 };
215 class PyDog : public Dog {
216 public:
217 using Dog::Dog; // Inherit constructors
218 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Dog, go, n_times); }
219 std::string name() override { PYBIND11_OVERLOAD(std::string, Dog, name, ); }
220 std::string bark() override { PYBIND11_OVERLOAD(std::string, Dog, bark, ); }
221 };
222
223A registered class derived from a pybind11-registered class with virtual
224methods requires a similar trampoline class, *even if* it doesn't explicitly
225declare or override any virtual methods itself:
226
227.. code-block:: cpp
228
229 class Husky : public Dog {};
230 class PyHusky : public Husky {
myd73499b815ad2017-01-13 18:15:52 +0800231 public:
232 using Husky::Husky; // Inherit constructors
Dean Moldovan67b52d82016-10-16 19:12:43 +0200233 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Husky, go, n_times); }
234 std::string name() override { PYBIND11_OVERLOAD(std::string, Husky, name, ); }
235 std::string bark() override { PYBIND11_OVERLOAD(std::string, Husky, bark, ); }
236 };
237
238There is, however, a technique that can be used to avoid this duplication
239(which can be especially helpful for a base class with several virtual
240methods). The technique involves using template trampoline classes, as
241follows:
242
243.. code-block:: cpp
244
245 template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
myd73499b815ad2017-01-13 18:15:52 +0800246 public:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200247 using AnimalBase::AnimalBase; // Inherit constructors
248 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, AnimalBase, go, n_times); }
249 std::string name() override { PYBIND11_OVERLOAD(std::string, AnimalBase, name, ); }
250 };
251 template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
myd73499b815ad2017-01-13 18:15:52 +0800252 public:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200253 using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
254 // Override PyAnimal's pure virtual go() with a non-pure one:
255 std::string go(int n_times) override { PYBIND11_OVERLOAD(std::string, DogBase, go, n_times); }
256 std::string bark() override { PYBIND11_OVERLOAD(std::string, DogBase, bark, ); }
257 };
258
259This technique has the advantage of requiring just one trampoline method to be
260declared per virtual method and pure virtual method override. It does,
261however, require the compiler to generate at least as many methods (and
262possibly more, if both pure virtual and overridden pure virtual methods are
263exposed, as above).
264
265The classes are then registered with pybind11 using:
266
267.. code-block:: cpp
268
269 py::class_<Animal, PyAnimal<>> animal(m, "Animal");
270 py::class_<Dog, PyDog<>> dog(m, "Dog");
271 py::class_<Husky, PyDog<Husky>> husky(m, "Husky");
272 // ... add animal, dog, husky definitions
273
274Note that ``Husky`` did not require a dedicated trampoline template class at
275all, since it neither declares any new virtual methods nor provides any pure
276virtual method implementations.
277
278With either the repeated-virtuals or templated trampoline methods in place, you
279can now create a python class that inherits from ``Dog``:
280
281.. code-block:: python
282
283 class ShihTzu(Dog):
284 def bark(self):
285 return "yip!"
286
287.. seealso::
288
289 See the file :file:`tests/test_virtual_functions.cpp` for complete examples
290 using both the duplication and templated trampoline approaches.
291
292Extended trampoline class functionality
293=======================================
294
295The trampoline classes described in the previous sections are, by default, only
296initialized when needed. More specifically, they are initialized when a python
297class actually inherits from a registered type (instead of merely creating an
298instance of the registered type), or when a registered constructor is only
299valid for the trampoline class but not the registered class. This is primarily
300for performance reasons: when the trampoline class is not needed for anything
301except virtual method dispatching, not initializing the trampoline class
302improves performance by avoiding needing to do a run-time check to see if the
303inheriting python instance has an overloaded method.
304
305Sometimes, however, it is useful to always initialize a trampoline class as an
306intermediate class that does more than just handle virtual method dispatching.
307For example, such a class might perform extra class initialization, extra
308destruction operations, and might define new members and methods to enable a
309more python-like interface to a class.
310
311In order to tell pybind11 that it should *always* initialize the trampoline
312class when creating new instances of a type, the class constructors should be
313declared using ``py::init_alias<Args, ...>()`` instead of the usual
314``py::init<Args, ...>()``. This forces construction via the trampoline class,
315ensuring member initialization and (eventual) destruction.
316
317.. seealso::
318
319 See the file :file:`tests/test_alias_initialization.cpp` for complete examples
320 showing both normal and forced trampoline instantiation.
321
322.. _custom_constructors:
323
324Custom constructors
325===================
326
327The syntax for binding constructors was previously introduced, but it only
328works when a constructor with the given parameters actually exists on the C++
329side. To extend this to more general cases, let's take a look at what actually
330happens under the hood: the following statement
331
332.. code-block:: cpp
333
334 py::class_<Example>(m, "Example")
335 .def(py::init<int>());
336
337is short hand notation for
338
339.. code-block:: cpp
340
341 py::class_<Example>(m, "Example")
342 .def("__init__",
343 [](Example &instance, int arg) {
344 new (&instance) Example(arg);
345 }
346 );
347
348In other words, :func:`init` creates an anonymous function that invokes an
349in-place constructor. Memory allocation etc. is already take care of beforehand
350within pybind11.
351
352.. _classes_with_non_public_destructors:
353
354Non-public destructors
355======================
356
357If a class has a private or protected destructor (as might e.g. be the case in
358a singleton pattern), a compile error will occur when creating bindings via
359pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
360is responsible for managing the lifetime of instances will reference the
361destructor even if no deallocations ever take place. In order to expose classes
362with private or protected destructors, it is possible to override the holder
363type via a holder type argument to ``class_``. Pybind11 provides a helper class
364``py::nodelete`` that disables any destructor invocations. In this case, it is
365crucial that instances are deallocated on the C++ side to avoid memory leaks.
366
367.. code-block:: cpp
368
369 /* ... definition ... */
370
371 class MyClass {
372 private:
373 ~MyClass() { }
374 };
375
376 /* ... binding code ... */
377
378 py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
myd73499b815ad2017-01-13 18:15:52 +0800379 .def(py::init<>())
Dean Moldovan67b52d82016-10-16 19:12:43 +0200380
381Implicit conversions
382====================
383
384Suppose that instances of two types ``A`` and ``B`` are used in a project, and
385that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
386could be a fixed and an arbitrary precision number type).
387
388.. code-block:: cpp
389
390 py::class_<A>(m, "A")
391 /// ... members ...
392
393 py::class_<B>(m, "B")
394 .def(py::init<A>())
395 /// ... members ...
396
397 m.def("func",
398 [](const B &) { /* .... */ }
399 );
400
401To invoke the function ``func`` using a variable ``a`` containing an ``A``
402instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
403will automatically apply an implicit type conversion, which makes it possible
404to directly write ``func(a)``.
405
406In this situation (i.e. where ``B`` has a constructor that converts from
407``A``), the following statement enables similar implicit conversions on the
408Python side:
409
410.. code-block:: cpp
411
412 py::implicitly_convertible<A, B>();
413
414.. note::
415
416 Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
417 data type that is exposed to Python via pybind11.
418
419.. _static_properties:
420
421Static properties
422=================
423
424The section on :ref:`properties` discussed the creation of instance properties
425that are implemented in terms of C++ getters and setters.
426
427Static properties can also be created in a similar way to expose getters and
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100428setters of static class attributes. Two things are important to note:
429
4301. Static properties are implemented by instrumenting the *metaclass* of the
431 class in question -- however, this requires the class to have a modifiable
432 metaclass in the first place. pybind11 provides a ``py::metaclass()``
433 annotation that must be specified in the ``class_`` constructor, or any
434 later method calls to ``def_{property_,∅}_{readwrite,readonly}_static`` will
435 fail (see the example below).
436
4372. For static properties defined in terms of setter and getter functions, note
438 that the implicit ``self`` argument also exists in this case and is used to
439 pass the Python ``type`` subclass instance. This parameter will often not be
440 needed by the C++ side, and the following example illustrates how to
441 instantiate a lambda getter function that ignores it:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200442
443.. code-block:: cpp
444
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100445 py::class_<Foo>(m, "Foo", py::metaclass())
Dean Moldovan67b52d82016-10-16 19:12:43 +0200446 .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
447
448Operator overloading
449====================
450
451Suppose that we're given the following ``Vector2`` class with a vector addition
452and scalar multiplication operation, all implemented using overloaded operators
453in C++.
454
455.. code-block:: cpp
456
457 class Vector2 {
458 public:
459 Vector2(float x, float y) : x(x), y(y) { }
460
461 Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
462 Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
463 Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
464 Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
465
466 friend Vector2 operator*(float f, const Vector2 &v) {
467 return Vector2(f * v.x, f * v.y);
468 }
469
470 std::string toString() const {
471 return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
472 }
473 private:
474 float x, y;
475 };
476
477The following snippet shows how the above operators can be conveniently exposed
478to Python.
479
480.. code-block:: cpp
481
482 #include <pybind11/operators.h>
483
484 PYBIND11_PLUGIN(example) {
485 py::module m("example", "pybind11 example plugin");
486
487 py::class_<Vector2>(m, "Vector2")
488 .def(py::init<float, float>())
489 .def(py::self + py::self)
490 .def(py::self += py::self)
491 .def(py::self *= float())
492 .def(float() * py::self)
myd73499b815ad2017-01-13 18:15:52 +0800493 .def(py::self * float())
Dean Moldovan67b52d82016-10-16 19:12:43 +0200494 .def("__repr__", &Vector2::toString);
495
496 return m.ptr();
497 }
498
499Note that a line like
500
501.. code-block:: cpp
502
503 .def(py::self * float())
504
505is really just short hand notation for
506
507.. code-block:: cpp
508
509 .def("__mul__", [](const Vector2 &a, float b) {
510 return a * b;
511 }, py::is_operator())
512
513This can be useful for exposing additional operators that don't exist on the
514C++ side, or to perform other types of customization. The ``py::is_operator``
515flag marker is needed to inform pybind11 that this is an operator, which
516returns ``NotImplemented`` when invoked with incompatible arguments rather than
517throwing a type error.
518
519.. note::
520
521 To use the more convenient ``py::self`` notation, the additional
522 header file :file:`pybind11/operators.h` must be included.
523
524.. seealso::
525
526 The file :file:`tests/test_operator_overloading.cpp` contains a
527 complete example that demonstrates how to work with overloaded operators in
528 more detail.
529
530Pickling support
531================
532
533Python's ``pickle`` module provides a powerful facility to serialize and
534de-serialize a Python object graph into a binary data stream. To pickle and
535unpickle C++ classes using pybind11, two additional functions must be provided.
536Suppose the class in question has the following signature:
537
538.. code-block:: cpp
539
540 class Pickleable {
541 public:
542 Pickleable(const std::string &value) : m_value(value) { }
543 const std::string &value() const { return m_value; }
544
545 void setExtra(int extra) { m_extra = extra; }
546 int extra() const { return m_extra; }
547 private:
548 std::string m_value;
549 int m_extra = 0;
550 };
551
552The binding code including the requisite ``__setstate__`` and ``__getstate__`` methods [#f3]_
553looks as follows:
554
555.. code-block:: cpp
556
557 py::class_<Pickleable>(m, "Pickleable")
558 .def(py::init<std::string>())
559 .def("value", &Pickleable::value)
560 .def("extra", &Pickleable::extra)
561 .def("setExtra", &Pickleable::setExtra)
562 .def("__getstate__", [](const Pickleable &p) {
563 /* Return a tuple that fully encodes the state of the object */
564 return py::make_tuple(p.value(), p.extra());
565 })
566 .def("__setstate__", [](Pickleable &p, py::tuple t) {
567 if (t.size() != 2)
568 throw std::runtime_error("Invalid state!");
569
570 /* Invoke the in-place constructor. Note that this is needed even
571 when the object just has a trivial default constructor */
572 new (&p) Pickleable(t[0].cast<std::string>());
573
574 /* Assign any additional state */
575 p.setExtra(t[1].cast<int>());
576 });
577
578An instance can now be pickled as follows:
579
580.. code-block:: python
581
582 try:
583 import cPickle as pickle # Use cPickle on Python 2.7
584 except ImportError:
585 import pickle
586
587 p = Pickleable("test_value")
588 p.setExtra(15)
589 data = pickle.dumps(p, 2)
590
591Note that only the cPickle module is supported on Python 2.7. The second
592argument to ``dumps`` is also crucial: it selects the pickle protocol version
5932, since the older version 1 is not supported. Newer versions are also fine—for
594instance, specify ``-1`` to always use the latest available version. Beware:
595failure to follow these instructions will cause important pybind11 memory
596allocation routines to be skipped during unpickling, which will likely lead to
597memory corruption and/or segmentation faults.
598
599.. seealso::
600
601 The file :file:`tests/test_pickling.cpp` contains a complete example
602 that demonstrates how to pickle and unpickle types using pybind11 in more
603 detail.
604
605.. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
606
607Multiple Inheritance
608====================
609
610pybind11 can create bindings for types that derive from multiple base types
611(aka. *multiple inheritance*). To do so, specify all bases in the template
612arguments of the ``class_`` declaration:
613
614.. code-block:: cpp
615
616 py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
617 ...
618
619The base types can be specified in arbitrary order, and they can even be
620interspersed with alias types and holder types (discussed earlier in this
621document)---pybind11 will automatically find out which is which. The only
622requirement is that the first template argument is the type to be declared.
623
624There are two caveats regarding the implementation of this feature:
625
6261. When only one base type is specified for a C++ type that actually has
627 multiple bases, pybind11 will assume that it does not participate in
628 multiple inheritance, which can lead to undefined behavior. In such cases,
629 add the tag ``multiple_inheritance``:
630
631 .. code-block:: cpp
632
633 py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
634
635 The tag is redundant and does not need to be specified when multiple base
636 types are listed.
637
6382. As was previously discussed in the section on :ref:`overriding_virtuals`, it
639 is easy to create Python types that derive from C++ classes. It is even
640 possible to make use of multiple inheritance to declare a Python class which
641 has e.g. a C++ and a Python class as bases. However, any attempt to create a
642 type that has *two or more* C++ classes in its hierarchy of base types will
643 fail with a fatal error message: ``TypeError: multiple bases have instance
644 lay-out conflict``. Core Python types that are implemented in C (e.g.
645 ``dict``, ``list``, ``Exception``, etc.) also fall under this combination
646 and cannot be combined with C++ types bound using pybind11 via multiple
647 inheritance.