blob: be4bc2e775d4b4e80aafe859d687aaae4df93adb [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
Dean Moldovan443ab592017-04-24 01:51:44 +020048 PYBIND11_MODULE(example, m) {
Dean Moldovan67b52d82016-10-16 19:12:43 +020049 py::class_<Animal> animal(m, "Animal");
50 animal
51 .def("go", &Animal::go);
52
53 py::class_<Dog>(m, "Dog", animal)
54 .def(py::init<>());
55
56 m.def("call_go", &call_go);
Dean Moldovan67b52d82016-10-16 19:12:43 +020057 }
58
59However, these bindings are impossible to extend: ``Animal`` is not
60constructible, and we clearly require some kind of "trampoline" that
61redirects virtual calls back to Python.
62
63Defining a new type of ``Animal`` from within Python is possible but requires a
64helper class that is defined as follows:
65
66.. code-block:: cpp
67
68 class PyAnimal : public Animal {
69 public:
70 /* Inherit the constructors */
71 using Animal::Animal;
72
73 /* Trampoline (need one for each virtual function) */
74 std::string go(int n_times) override {
75 PYBIND11_OVERLOAD_PURE(
76 std::string, /* Return type */
77 Animal, /* Parent class */
jbarlow837830e852017-01-13 02:17:29 -080078 go, /* Name of function in C++ (must match Python name) */
Dean Moldovan67b52d82016-10-16 19:12:43 +020079 n_times /* Argument(s) */
80 );
81 }
82 };
83
84The macro :func:`PYBIND11_OVERLOAD_PURE` should be used for pure virtual
85functions, and :func:`PYBIND11_OVERLOAD` should be used for functions which have
86a default implementation. There are also two alternate macros
87:func:`PYBIND11_OVERLOAD_PURE_NAME` and :func:`PYBIND11_OVERLOAD_NAME` which
88take a string-valued name argument between the *Parent class* and *Name of the
Dean Moldovan234f7c32017-08-17 17:03:46 +020089function* slots, which defines the name of function in Python. This is required
jbarlow837830e852017-01-13 02:17:29 -080090when the C++ and Python versions of the
Dean Moldovan67b52d82016-10-16 19:12:43 +020091function have different names, e.g. ``operator()`` vs ``__call__``.
92
93The binding code also needs a few minor adaptations (highlighted):
94
95.. code-block:: cpp
Dean Moldovan443ab592017-04-24 01:51:44 +020096 :emphasize-lines: 2,4,5
Dean Moldovan67b52d82016-10-16 19:12:43 +020097
Dean Moldovan443ab592017-04-24 01:51:44 +020098 PYBIND11_MODULE(example, m) {
Dean Moldovan67b52d82016-10-16 19:12:43 +020099 py::class_<Animal, PyAnimal /* <--- trampoline*/> animal(m, "Animal");
100 animal
101 .def(py::init<>())
102 .def("go", &Animal::go);
103
104 py::class_<Dog>(m, "Dog", animal)
105 .def(py::init<>());
106
107 m.def("call_go", &call_go);
Dean Moldovan67b52d82016-10-16 19:12:43 +0200108 }
109
110Importantly, pybind11 is made aware of the trampoline helper class by
jbarlow837830e852017-01-13 02:17:29 -0800111specifying it as an extra template argument to :class:`class_`. (This can also
Dean Moldovan67b52d82016-10-16 19:12:43 +0200112be combined with other template arguments such as a custom holder type; the
113order of template types does not matter). Following this, we are able to
114define a constructor as usual.
115
jbarlow837830e852017-01-13 02:17:29 -0800116Bindings should be made against the actual class, not the trampoline helper class.
117
118.. code-block:: cpp
119
120 py::class_<Animal, PyAnimal /* <--- trampoline*/> animal(m, "Animal");
121 animal
122 .def(py::init<>())
123 .def("go", &PyAnimal::go); /* <--- THIS IS WRONG, use &Animal::go */
124
Dean Moldovan67b52d82016-10-16 19:12:43 +0200125Note, however, that the above is sufficient for allowing python classes to
EricCousineau-TRIe06077b2017-08-07 18:37:42 -0400126extend ``Animal``, but not ``Dog``: see :ref:`virtual_and_inheritance` for the
Dean Moldovan67b52d82016-10-16 19:12:43 +0200127necessary steps required to providing proper overload support for inherited
128classes.
129
130The Python session below shows how to override ``Animal::go`` and invoke it via
131a virtual method call.
132
133.. code-block:: pycon
134
135 >>> from example import *
136 >>> d = Dog()
137 >>> call_go(d)
138 u'woof! woof! woof! '
139 >>> class Cat(Animal):
140 ... def go(self, n_times):
141 ... return "meow! " * n_times
142 ...
143 >>> c = Cat()
144 >>> call_go(c)
145 u'meow! meow! meow! '
146
EricCousineau-TRIe06077b2017-08-07 18:37:42 -0400147If you are defining a custom constructor in a derived Python class, you *must*
148ensure that you explicitly call the bound C++ constructor using ``__init__``,
149*regardless* of whether it is a default constructor or not. Otherwise, the
150memory for the C++ portion of the instance will be left uninitialized, which
151will generally leave the C++ instance in an invalid state and cause undefined
152behavior if the C++ instance is subsequently used.
153
154Here is an example:
155
156.. code-block:: python
157
158 class Dachschund(Dog):
159 def __init__(self, name):
160 Dog.__init__(self) # Without this, undefind behavior may occur if the C++ portions are referenced.
161 self.name = name
162 def bark(self):
163 return "yap!"
164
165Note that a direct ``__init__`` constructor *should be called*, and ``super()``
166should not be used. For simple cases of linear inheritance, ``super()``
167may work, but once you begin mixing Python and C++ multiple inheritance,
168things will fall apart due to differences between Python's MRO and C++'s
169mechanisms.
170
Dean Moldovan67b52d82016-10-16 19:12:43 +0200171Please take a look at the :ref:`macro_notes` before using this feature.
172
173.. note::
174
175 When the overridden type returns a reference or pointer to a type that
176 pybind11 converts from Python (for example, numeric values, std::string,
177 and other built-in value-converting types), there are some limitations to
178 be aware of:
179
180 - because in these cases there is no C++ variable to reference (the value
181 is stored in the referenced Python variable), pybind11 provides one in
182 the PYBIND11_OVERLOAD macros (when needed) with static storage duration.
183 Note that this means that invoking the overloaded method on *any*
184 instance will change the referenced value stored in *all* instances of
185 that type.
186
187 - Attempts to modify a non-const reference will not have the desired
188 effect: it will change only the static cache variable, but this change
189 will not propagate to underlying Python instance, and the change will be
190 replaced the next time the overload is invoked.
191
192.. seealso::
193
194 The file :file:`tests/test_virtual_functions.cpp` contains a complete
195 example that demonstrates how to override virtual functions using pybind11
196 in more detail.
197
198.. _virtual_and_inheritance:
199
200Combining virtual functions and inheritance
201===========================================
202
203When combining virtual methods with inheritance, you need to be sure to provide
204an override for each method for which you want to allow overrides from derived
205python classes. For example, suppose we extend the above ``Animal``/``Dog``
206example as follows:
207
208.. code-block:: cpp
209
210 class Animal {
211 public:
212 virtual std::string go(int n_times) = 0;
213 virtual std::string name() { return "unknown"; }
214 };
myd73499b815ad2017-01-13 18:15:52 +0800215 class Dog : public Animal {
Dean Moldovan67b52d82016-10-16 19:12:43 +0200216 public:
217 std::string go(int n_times) override {
218 std::string result;
219 for (int i=0; i<n_times; ++i)
220 result += bark() + " ";
221 return result;
222 }
223 virtual std::string bark() { return "woof!"; }
224 };
225
226then the trampoline class for ``Animal`` must, as described in the previous
227section, override ``go()`` and ``name()``, but in order to allow python code to
228inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
229overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
230methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
231override the ``name()`` method):
232
233.. code-block:: cpp
234
235 class PyAnimal : public Animal {
236 public:
237 using Animal::Animal; // Inherit constructors
238 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Animal, go, n_times); }
239 std::string name() override { PYBIND11_OVERLOAD(std::string, Animal, name, ); }
240 };
241 class PyDog : public Dog {
242 public:
243 using Dog::Dog; // Inherit constructors
244 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Dog, go, n_times); }
245 std::string name() override { PYBIND11_OVERLOAD(std::string, Dog, name, ); }
246 std::string bark() override { PYBIND11_OVERLOAD(std::string, Dog, bark, ); }
247 };
248
Wenzel Jakobab262592017-03-22 21:39:19 +0100249.. note::
250
251 Note the trailing commas in the ``PYBIND11_OVERLOAD`` calls to ``name()``
252 and ``bark()``. These are needed to portably implement a trampoline for a
253 function that does not take any arguments. For functions that take
254 a nonzero number of arguments, the trailing comma must be omitted.
255
Dean Moldovan67b52d82016-10-16 19:12:43 +0200256A registered class derived from a pybind11-registered class with virtual
257methods requires a similar trampoline class, *even if* it doesn't explicitly
258declare or override any virtual methods itself:
259
260.. code-block:: cpp
261
262 class Husky : public Dog {};
263 class PyHusky : public Husky {
myd73499b815ad2017-01-13 18:15:52 +0800264 public:
265 using Husky::Husky; // Inherit constructors
Dean Moldovan67b52d82016-10-16 19:12:43 +0200266 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Husky, go, n_times); }
267 std::string name() override { PYBIND11_OVERLOAD(std::string, Husky, name, ); }
268 std::string bark() override { PYBIND11_OVERLOAD(std::string, Husky, bark, ); }
269 };
270
271There is, however, a technique that can be used to avoid this duplication
272(which can be especially helpful for a base class with several virtual
273methods). The technique involves using template trampoline classes, as
274follows:
275
276.. code-block:: cpp
277
278 template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
myd73499b815ad2017-01-13 18:15:52 +0800279 public:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200280 using AnimalBase::AnimalBase; // Inherit constructors
281 std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, AnimalBase, go, n_times); }
282 std::string name() override { PYBIND11_OVERLOAD(std::string, AnimalBase, name, ); }
283 };
284 template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
myd73499b815ad2017-01-13 18:15:52 +0800285 public:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200286 using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
287 // Override PyAnimal's pure virtual go() with a non-pure one:
288 std::string go(int n_times) override { PYBIND11_OVERLOAD(std::string, DogBase, go, n_times); }
289 std::string bark() override { PYBIND11_OVERLOAD(std::string, DogBase, bark, ); }
290 };
291
292This technique has the advantage of requiring just one trampoline method to be
293declared per virtual method and pure virtual method override. It does,
294however, require the compiler to generate at least as many methods (and
295possibly more, if both pure virtual and overridden pure virtual methods are
296exposed, as above).
297
298The classes are then registered with pybind11 using:
299
300.. code-block:: cpp
301
302 py::class_<Animal, PyAnimal<>> animal(m, "Animal");
303 py::class_<Dog, PyDog<>> dog(m, "Dog");
304 py::class_<Husky, PyDog<Husky>> husky(m, "Husky");
305 // ... add animal, dog, husky definitions
306
307Note that ``Husky`` did not require a dedicated trampoline template class at
308all, since it neither declares any new virtual methods nor provides any pure
309virtual method implementations.
310
311With either the repeated-virtuals or templated trampoline methods in place, you
312can now create a python class that inherits from ``Dog``:
313
314.. code-block:: python
315
316 class ShihTzu(Dog):
317 def bark(self):
318 return "yip!"
319
320.. seealso::
321
322 See the file :file:`tests/test_virtual_functions.cpp` for complete examples
323 using both the duplication and templated trampoline approaches.
324
Jason Rhinelander464d9892017-06-12 21:52:48 -0400325.. _extended_aliases:
326
Dean Moldovan67b52d82016-10-16 19:12:43 +0200327Extended trampoline class functionality
328=======================================
329
330The trampoline classes described in the previous sections are, by default, only
331initialized when needed. More specifically, they are initialized when a python
332class actually inherits from a registered type (instead of merely creating an
333instance of the registered type), or when a registered constructor is only
334valid for the trampoline class but not the registered class. This is primarily
335for performance reasons: when the trampoline class is not needed for anything
336except virtual method dispatching, not initializing the trampoline class
337improves performance by avoiding needing to do a run-time check to see if the
338inheriting python instance has an overloaded method.
339
340Sometimes, however, it is useful to always initialize a trampoline class as an
341intermediate class that does more than just handle virtual method dispatching.
342For example, such a class might perform extra class initialization, extra
343destruction operations, and might define new members and methods to enable a
344more python-like interface to a class.
345
346In order to tell pybind11 that it should *always* initialize the trampoline
347class when creating new instances of a type, the class constructors should be
348declared using ``py::init_alias<Args, ...>()`` instead of the usual
349``py::init<Args, ...>()``. This forces construction via the trampoline class,
350ensuring member initialization and (eventual) destruction.
351
352.. seealso::
353
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200354 See the file :file:`tests/test_virtual_functions.cpp` for complete examples
Dean Moldovan67b52d82016-10-16 19:12:43 +0200355 showing both normal and forced trampoline instantiation.
356
357.. _custom_constructors:
358
359Custom constructors
360===================
361
362The syntax for binding constructors was previously introduced, but it only
Jason Rhinelander464d9892017-06-12 21:52:48 -0400363works when a constructor of the appropriate arguments actually exists on the
364C++ side. To extend this to more general cases, pybind11 offers two different
365approaches: binding factory functions, and placement-new creation.
366
367Factory function constructors
368-----------------------------
369
370It is possible to expose a Python-side constructor from a C++ function that
371returns a new object by value or pointer. For example, suppose you have a
372class like this:
373
374.. code-block:: cpp
375
376 class Example {
377 private:
378 Example(int); // private constructor
379 public:
380 // Factory function:
381 static Example create(int a) { return Example(a); }
382 };
383
Wenzel Jakobfb276c62017-08-22 00:55:53 +0200384While it is possible to create a straightforward binding of the static
385``create`` method, it may sometimes be preferable to expose it as a constructor
386on the Python side. This can be accomplished by calling ``.def(py::init(...))``
387with the function reference returning the new instance passed as an argument.
388It is also possible to use this approach to bind a function returning a new
389instance by raw pointer or by the holder (e.g. ``std::unique_ptr``).
Jason Rhinelander464d9892017-06-12 21:52:48 -0400390
391The following example shows the different approaches:
392
393.. code-block:: cpp
394
395 class Example {
396 private:
397 Example(int); // private constructor
398 public:
399 // Factory function - returned by value:
400 static Example create(int a) { return Example(a); }
401
402 // These constructors are publicly callable:
403 Example(double);
404 Example(int, int);
405 Example(std::string);
406 };
407
408 py::class_<Example>(m, "Example")
409 // Bind the factory function as a constructor:
410 .def(py::init(&Example::create))
411 // Bind a lambda function returning a pointer wrapped in a holder:
412 .def(py::init([](std::string arg) {
413 return std::unique_ptr<Example>(new Example(arg));
414 }))
415 // Return a raw pointer:
416 .def(py::init([](int a, int b) { return new Example(a, b); }))
417 // You can mix the above with regular C++ constructor bindings as well:
418 .def(py::init<double>())
419 ;
420
421When the constructor is invoked from Python, pybind11 will call the factory
422function and store the resulting C++ instance in the Python instance.
423
Wenzel Jakobfb276c62017-08-22 00:55:53 +0200424When combining factory functions constructors with :ref:`virtual function
425trampolines <overriding_virtuals>` there are two approaches. The first is to
426add a constructor to the alias class that takes a base value by
427rvalue-reference. If such a constructor is available, it will be used to
428construct an alias instance from the value returned by the factory function.
429The second option is to provide two factory functions to ``py::init()``: the
430first will be invoked when no alias class is required (i.e. when the class is
431being used but not inherited from in Python), and the second will be invoked
432when an alias is required.
Jason Rhinelander464d9892017-06-12 21:52:48 -0400433
434You can also specify a single factory function that always returns an alias
435instance: this will result in behaviour similar to ``py::init_alias<...>()``,
Wenzel Jakobfb276c62017-08-22 00:55:53 +0200436as described in the :ref:`extended trampoline class documentation
437<extended_aliases>`.
Jason Rhinelander464d9892017-06-12 21:52:48 -0400438
439The following example shows the different factory approaches for a class with
440an alias:
441
442.. code-block:: cpp
443
444 #include <pybind11/factory.h>
445 class Example {
446 public:
447 // ...
448 virtual ~Example() = default;
449 };
450 class PyExample : public Example {
451 public:
452 using Example::Example;
453 PyExample(Example &&base) : Example(std::move(base)) {}
454 };
455 py::class_<Example, PyExample>(m, "Example")
456 // Returns an Example pointer. If a PyExample is needed, the Example
457 // instance will be moved via the extra constructor in PyExample, above.
458 .def(py::init([]() { return new Example(); }))
459 // Two callbacks:
460 .def(py::init([]() { return new Example(); } /* no alias needed */,
461 []() { return new PyExample(); } /* alias needed */))
462 // *Always* returns an alias instance (like py::init_alias<>())
463 .def(py::init([]() { return new PyExample(); }))
464 ;
465
466Low-level placement-new construction
467------------------------------------
468
469A second approach for creating new instances use C++ placement new to construct
470an object in-place in preallocated memory. To do this, you simply bind a
471method name ``__init__`` that takes the class instance as the first argument by
472pointer or reference, then uses a placement-new constructor to construct the
473object in the pre-allocated (but uninitialized) memory.
474
475For example, instead of:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200476
477.. code-block:: cpp
478
479 py::class_<Example>(m, "Example")
480 .def(py::init<int>());
481
Jason Rhinelander464d9892017-06-12 21:52:48 -0400482you could equivalently write:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200483
484.. code-block:: cpp
485
486 py::class_<Example>(m, "Example")
487 .def("__init__",
488 [](Example &instance, int arg) {
489 new (&instance) Example(arg);
490 }
491 );
492
Jason Rhinelander464d9892017-06-12 21:52:48 -0400493which will invoke the constructor in-place at the pre-allocated memory.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200494
Wenzel Jakob4336a7d2017-08-21 22:48:28 +0200495Brace initialization
496--------------------
497
498``pybind11::init<>`` internally uses C++11 brace initialization to call the
499constructor of the target class. This means that it can be used to bind
500*implicit* constructors as well:
501
502.. code-block:: cpp
503
504 struct Aggregate {
505 int a;
506 std::string b;
507 };
508
509 py::class_<Aggregate>(m, "Aggregate")
510 .def(py::init<int, const std::string &>());
511
512.. note::
513
514 Note that brace initialization preferentially invokes constructor overloads
515 taking a ``std::initializer_list``. In the rare event that this causes an
516 issue, you can work around it by using ``py::init(...)`` with a lambda
517 function that constructs the new object as desired.
518
Dean Moldovan67b52d82016-10-16 19:12:43 +0200519.. _classes_with_non_public_destructors:
520
521Non-public destructors
522======================
523
524If a class has a private or protected destructor (as might e.g. be the case in
525a singleton pattern), a compile error will occur when creating bindings via
526pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
527is responsible for managing the lifetime of instances will reference the
528destructor even if no deallocations ever take place. In order to expose classes
529with private or protected destructors, it is possible to override the holder
530type via a holder type argument to ``class_``. Pybind11 provides a helper class
531``py::nodelete`` that disables any destructor invocations. In this case, it is
532crucial that instances are deallocated on the C++ side to avoid memory leaks.
533
534.. code-block:: cpp
535
536 /* ... definition ... */
537
538 class MyClass {
539 private:
540 ~MyClass() { }
541 };
542
543 /* ... binding code ... */
544
545 py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
myd73499b815ad2017-01-13 18:15:52 +0800546 .def(py::init<>())
Dean Moldovan67b52d82016-10-16 19:12:43 +0200547
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500548.. _implicit_conversions:
549
Dean Moldovan67b52d82016-10-16 19:12:43 +0200550Implicit conversions
551====================
552
553Suppose that instances of two types ``A`` and ``B`` are used in a project, and
554that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
555could be a fixed and an arbitrary precision number type).
556
557.. code-block:: cpp
558
559 py::class_<A>(m, "A")
560 /// ... members ...
561
562 py::class_<B>(m, "B")
563 .def(py::init<A>())
564 /// ... members ...
565
566 m.def("func",
567 [](const B &) { /* .... */ }
568 );
569
570To invoke the function ``func`` using a variable ``a`` containing an ``A``
571instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
572will automatically apply an implicit type conversion, which makes it possible
573to directly write ``func(a)``.
574
575In this situation (i.e. where ``B`` has a constructor that converts from
576``A``), the following statement enables similar implicit conversions on the
577Python side:
578
579.. code-block:: cpp
580
581 py::implicitly_convertible<A, B>();
582
583.. note::
584
585 Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
586 data type that is exposed to Python via pybind11.
587
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +0200588 To prevent runaway recursion, implicit conversions are non-reentrant: an
589 implicit conversion invoked as part of another implicit conversion of the
590 same type (i.e. from ``A`` to ``B``) will fail.
591
Dean Moldovan67b52d82016-10-16 19:12:43 +0200592.. _static_properties:
593
594Static properties
595=================
596
597The section on :ref:`properties` discussed the creation of instance properties
598that are implemented in terms of C++ getters and setters.
599
600Static properties can also be created in a similar way to expose getters and
Dean Moldovandd016652017-02-16 23:02:56 +0100601setters of static class attributes. Note that the implicit ``self`` argument
602also exists in this case and is used to pass the Python ``type`` subclass
603instance. This parameter will often not be needed by the C++ side, and the
604following example illustrates how to instantiate a lambda getter function
605that ignores it:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200606
607.. code-block:: cpp
608
Dean Moldovandd016652017-02-16 23:02:56 +0100609 py::class_<Foo>(m, "Foo")
Dean Moldovan67b52d82016-10-16 19:12:43 +0200610 .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
611
612Operator overloading
613====================
614
615Suppose that we're given the following ``Vector2`` class with a vector addition
616and scalar multiplication operation, all implemented using overloaded operators
617in C++.
618
619.. code-block:: cpp
620
621 class Vector2 {
622 public:
623 Vector2(float x, float y) : x(x), y(y) { }
624
625 Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
626 Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
627 Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
628 Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
629
630 friend Vector2 operator*(float f, const Vector2 &v) {
631 return Vector2(f * v.x, f * v.y);
632 }
633
634 std::string toString() const {
635 return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
636 }
637 private:
638 float x, y;
639 };
640
641The following snippet shows how the above operators can be conveniently exposed
642to Python.
643
644.. code-block:: cpp
645
646 #include <pybind11/operators.h>
647
Dean Moldovan443ab592017-04-24 01:51:44 +0200648 PYBIND11_MODULE(example, m) {
Dean Moldovan67b52d82016-10-16 19:12:43 +0200649 py::class_<Vector2>(m, "Vector2")
650 .def(py::init<float, float>())
651 .def(py::self + py::self)
652 .def(py::self += py::self)
653 .def(py::self *= float())
654 .def(float() * py::self)
myd73499b815ad2017-01-13 18:15:52 +0800655 .def(py::self * float())
Dean Moldovan67b52d82016-10-16 19:12:43 +0200656 .def("__repr__", &Vector2::toString);
Dean Moldovan67b52d82016-10-16 19:12:43 +0200657 }
658
659Note that a line like
660
661.. code-block:: cpp
662
663 .def(py::self * float())
664
665is really just short hand notation for
666
667.. code-block:: cpp
668
669 .def("__mul__", [](const Vector2 &a, float b) {
670 return a * b;
671 }, py::is_operator())
672
673This can be useful for exposing additional operators that don't exist on the
674C++ side, or to perform other types of customization. The ``py::is_operator``
675flag marker is needed to inform pybind11 that this is an operator, which
676returns ``NotImplemented`` when invoked with incompatible arguments rather than
677throwing a type error.
678
679.. note::
680
681 To use the more convenient ``py::self`` notation, the additional
682 header file :file:`pybind11/operators.h` must be included.
683
684.. seealso::
685
686 The file :file:`tests/test_operator_overloading.cpp` contains a
687 complete example that demonstrates how to work with overloaded operators in
688 more detail.
689
Dean Moldovan1e5a7da2017-08-24 01:53:15 +0200690.. _pickling:
691
Dean Moldovan67b52d82016-10-16 19:12:43 +0200692Pickling support
693================
694
695Python's ``pickle`` module provides a powerful facility to serialize and
696de-serialize a Python object graph into a binary data stream. To pickle and
Dean Moldovan1e5a7da2017-08-24 01:53:15 +0200697unpickle C++ classes using pybind11, a ``py::pickle()`` definition must be
698provided. Suppose the class in question has the following signature:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200699
700.. code-block:: cpp
701
702 class Pickleable {
703 public:
704 Pickleable(const std::string &value) : m_value(value) { }
705 const std::string &value() const { return m_value; }
706
707 void setExtra(int extra) { m_extra = extra; }
708 int extra() const { return m_extra; }
709 private:
710 std::string m_value;
711 int m_extra = 0;
712 };
713
Dean Moldovan1e5a7da2017-08-24 01:53:15 +0200714Pickling support in Python is enable by defining the ``__setstate__`` and
715``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()``
716to bind these two functions:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200717
718.. code-block:: cpp
719
720 py::class_<Pickleable>(m, "Pickleable")
721 .def(py::init<std::string>())
722 .def("value", &Pickleable::value)
723 .def("extra", &Pickleable::extra)
724 .def("setExtra", &Pickleable::setExtra)
Dean Moldovan1e5a7da2017-08-24 01:53:15 +0200725 .def(py::pickle(
726 [](const Pickleable &p) { // __getstate__
727 /* Return a tuple that fully encodes the state of the object */
728 return py::make_tuple(p.value(), p.extra());
729 },
730 [](py::tuple t) { // __setstate__
731 if (t.size() != 2)
732 throw std::runtime_error("Invalid state!");
Dean Moldovan67b52d82016-10-16 19:12:43 +0200733
Dean Moldovan1e5a7da2017-08-24 01:53:15 +0200734 /* Create a new C++ instance */
735 Pickleable p(t[0].cast<std::string>());
Dean Moldovan67b52d82016-10-16 19:12:43 +0200736
Dean Moldovan1e5a7da2017-08-24 01:53:15 +0200737 /* Assign any additional state */
738 p.setExtra(t[1].cast<int>());
739
740 return p;
741 }
742 ));
743
744The ``__setstate__`` part of the ``py::picke()`` definition follows the same
745rules as the single-argument version of ``py::init()``. The return type can be
746a value, pointer or holder type. See :ref:`custom_constructors` for details.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200747
748An instance can now be pickled as follows:
749
750.. code-block:: python
751
752 try:
753 import cPickle as pickle # Use cPickle on Python 2.7
754 except ImportError:
755 import pickle
756
757 p = Pickleable("test_value")
758 p.setExtra(15)
759 data = pickle.dumps(p, 2)
760
761Note that only the cPickle module is supported on Python 2.7. The second
762argument to ``dumps`` is also crucial: it selects the pickle protocol version
7632, since the older version 1 is not supported. Newer versions are also fine—for
764instance, specify ``-1`` to always use the latest available version. Beware:
765failure to follow these instructions will cause important pybind11 memory
766allocation routines to be skipped during unpickling, which will likely lead to
767memory corruption and/or segmentation faults.
768
769.. seealso::
770
771 The file :file:`tests/test_pickling.cpp` contains a complete example
772 that demonstrates how to pickle and unpickle types using pybind11 in more
773 detail.
774
775.. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
776
777Multiple Inheritance
778====================
779
780pybind11 can create bindings for types that derive from multiple base types
781(aka. *multiple inheritance*). To do so, specify all bases in the template
782arguments of the ``class_`` declaration:
783
784.. code-block:: cpp
785
786 py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
787 ...
788
789The base types can be specified in arbitrary order, and they can even be
790interspersed with alias types and holder types (discussed earlier in this
791document)---pybind11 will automatically find out which is which. The only
792requirement is that the first template argument is the type to be declared.
793
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500794It is also permitted to inherit multiply from exported C++ classes in Python,
795as well as inheriting from multiple Python and/or pybind-exported classes.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200796
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500797There is one caveat regarding the implementation of this feature:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200798
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500799When only one base type is specified for a C++ type that actually has multiple
800bases, pybind11 will assume that it does not participate in multiple
801inheritance, which can lead to undefined behavior. In such cases, add the tag
802``multiple_inheritance`` to the class constructor:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200803
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500804.. code-block:: cpp
Dean Moldovan67b52d82016-10-16 19:12:43 +0200805
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500806 py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
Dean Moldovan67b52d82016-10-16 19:12:43 +0200807
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500808The tag is redundant and does not need to be specified when multiple base types
809are listed.
Jason Rhinelander7437c692017-07-28 22:03:44 -0400810
811.. _module_local:
812
813Module-local class bindings
814===========================
815
816When creating a binding for a class, pybind by default makes that binding
817"global" across modules. What this means is that a type defined in one module
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400818can be returned from any module resulting in the same Python type. For
Jason Rhinelander7437c692017-07-28 22:03:44 -0400819example, this allows the following:
820
821.. code-block:: cpp
822
823 // In the module1.cpp binding code for module1:
824 py::class_<Pet>(m, "Pet")
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400825 .def(py::init<std::string>())
826 .def_readonly("name", &Pet::name);
Jason Rhinelander7437c692017-07-28 22:03:44 -0400827
828.. code-block:: cpp
829
830 // In the module2.cpp binding code for module2:
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400831 m.def("create_pet", [](std::string name) { return new Pet(name); });
Jason Rhinelander7437c692017-07-28 22:03:44 -0400832
833.. code-block:: pycon
834
835 >>> from module1 import Pet
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400836 >>> from module2 import create_pet
837 >>> pet1 = Pet("Kitty")
838 >>> pet2 = create_pet("Doggy")
839 >>> pet2.name()
840 'Doggy'
Jason Rhinelander7437c692017-07-28 22:03:44 -0400841
842When writing binding code for a library, this is usually desirable: this
843allows, for example, splitting up a complex library into multiple Python
844modules.
845
846In some cases, however, this can cause conflicts. For example, suppose two
847unrelated modules make use of an external C++ library and each provide custom
848bindings for one of that library's classes. This will result in an error when
849a Python program attempts to import both modules (directly or indirectly)
850because of conflicting definitions on the external type:
851
852.. code-block:: cpp
853
854 // dogs.cpp
855
856 // Binding for external library class:
857 py::class<pets::Pet>(m, "Pet")
858 .def("name", &pets::Pet::name);
859
860 // Binding for local extension class:
861 py::class<Dog, pets::Pet>(m, "Dog")
862 .def(py::init<std::string>());
863
864.. code-block:: cpp
865
866 // cats.cpp, in a completely separate project from the above dogs.cpp.
867
868 // Binding for external library class:
869 py::class<pets::Pet>(m, "Pet")
870 .def("get_name", &pets::Pet::name);
871
872 // Binding for local extending class:
873 py::class<Cat, pets::Pet>(m, "Cat")
874 .def(py::init<std::string>());
875
876.. code-block:: pycon
877
878 >>> import cats
879 >>> import dogs
880 Traceback (most recent call last):
881 File "<stdin>", line 1, in <module>
882 ImportError: generic_type: type "Pet" is already registered!
883
884To get around this, you can tell pybind11 to keep the external class binding
885localized to the module by passing the ``py::module_local()`` attribute into
886the ``py::class_`` constructor:
887
888.. code-block:: cpp
889
890 // Pet binding in dogs.cpp:
891 py::class<pets::Pet>(m, "Pet", py::module_local())
892 .def("name", &pets::Pet::name);
893
894.. code-block:: cpp
895
896 // Pet binding in cats.cpp:
897 py::class<pets::Pet>(m, "Pet", py::module_local())
898 .def("get_name", &pets::Pet::name);
899
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400900This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes,
901avoiding the conflict and allowing both modules to be loaded. C++ code in the
902``dogs`` module that casts or returns a ``Pet`` instance will result in a
903``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result
904in a ``cats.Pet`` Python instance.
Jason Rhinelander7437c692017-07-28 22:03:44 -0400905
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400906This does come with two caveats, however: First, external modules cannot return
907or cast a ``Pet`` instance to Python (unless they also provide their own local
908bindings). Second, from the Python point of view they are two distinct classes.
909
910Note that the locality only applies in the C++ -> Python direction. When
911passing such a ``py::module_local`` type into a C++ function, the module-local
912classes are still considered. This means that if the following function is
913added to any module (including but not limited to the ``cats`` and ``dogs``
914modules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet``
915argument:
Jason Rhinelander7437c692017-07-28 22:03:44 -0400916
917.. code-block:: cpp
918
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400919 m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); });
Jason Rhinelander7437c692017-07-28 22:03:44 -0400920
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400921For example, suppose the above function is added to each of ``cats.cpp``,
922``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that
923does *not* bind ``Pets`` at all).
Jason Rhinelander7437c692017-07-28 22:03:44 -0400924
925.. code-block:: pycon
926
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400927 >>> import cats, dogs, frogs # No error because of the added py::module_local()
Jason Rhinelander7437c692017-07-28 22:03:44 -0400928 >>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover")
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400929 >>> (cats.pet_name(mycat), dogs.pet_name(mydog))
Jason Rhinelander7437c692017-07-28 22:03:44 -0400930 ('Fluffy', 'Rover')
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400931 >>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat))
932 ('Rover', 'Fluffy', 'Fluffy')
Jason Rhinelander7437c692017-07-28 22:03:44 -0400933
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400934It is possible to use ``py::module_local()`` registrations in one module even
935if another module registers the same type globally: within the module with the
936module-local definition, all C++ instances will be cast to the associated bound
937Python type. In other modules any such values are converted to the global
938Python type created elsewhere.
Jason Rhinelander4b159232017-08-04 13:05:12 -0400939
Jason Rhinelander7437c692017-07-28 22:03:44 -0400940.. note::
941
942 STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`
943 header) apply ``py::module_local`` by default when the bound type might
944 conflict with other modules; see :ref:`stl_bind` for details.
945
946.. note::
947
948 The localization of the bound types is actually tied to the shared object
949 or binary generated by the compiler/linker. For typical modules created
950 with ``PYBIND11_MODULE()``, this distinction is not significant. It is
951 possible, however, when :ref:`embedding` to embed multiple modules in the
952 same binary (see :ref:`embedding_modules`). In such a case, the
953 localization will apply across all embedded modules within the same binary.
954
955.. seealso::
956
957 The file :file:`tests/test_local_bindings.cpp` contains additional examples
958 that demonstrate how ``py::module_local()`` works.
Dean Moldovan234f7c32017-08-17 17:03:46 +0200959
960Binding protected member functions
961==================================
962
963It's normally not possible to expose ``protected`` member functions to Python:
964
965.. code-block:: cpp
966
967 class A {
968 protected:
969 int foo() const { return 42; }
970 };
971
972 py::class_<A>(m, "A")
973 .def("foo", &A::foo); // error: 'foo' is a protected member of 'A'
974
975On one hand, this is good because non-``public`` members aren't meant to be
976accessed from the outside. But we may want to make use of ``protected``
977functions in derived Python classes.
978
979The following pattern makes this possible:
980
981.. code-block:: cpp
982
983 class A {
984 protected:
985 int foo() const { return 42; }
986 };
987
988 class Publicist : public A { // helper type for exposing protected functions
989 public:
990 using A::foo; // inherited with different access modifier
991 };
992
993 py::class_<A>(m, "A") // bind the primary class
994 .def("foo", &Publicist::foo); // expose protected methods via the publicist
995
996This works because ``&Publicist::foo`` is exactly the same function as
997``&A::foo`` (same signature and address), just with a different access
998modifier. The only purpose of the ``Publicist`` helper class is to make
999the function name ``public``.
1000
1001If the intent is to expose ``protected`` ``virtual`` functions which can be
1002overridden in Python, the publicist pattern can be combined with the previously
1003described trampoline:
1004
1005.. code-block:: cpp
1006
1007 class A {
1008 public:
1009 virtual ~A() = default;
1010
1011 protected:
1012 virtual int foo() const { return 42; }
1013 };
1014
1015 class Trampoline : public A {
1016 public:
1017 int foo() const override { PYBIND11_OVERLOAD(int, A, foo, ); }
1018 };
1019
1020 class Publicist : public A {
1021 public:
1022 using A::foo;
1023 };
1024
1025 py::class_<A, Trampoline>(m, "A") // <-- `Trampoline` here
1026 .def("foo", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`!
1027
1028.. note::
1029
1030 MSVC 2015 has a compiler bug (fixed in version 2017) which
1031 requires a more explicit function binding in the form of
1032 ``.def("foo", static_cast<int (A::*)() const>(&Publicist::foo));``
1033 where ``int (A::*)() const`` is the type of ``A::foo``.