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