blob: 20853be2aca4cfc946d529efb23581e4a0ffe8dc [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
jbarlow837830e852017-01-13 02:17:29 -080089function* slots, which defines the name of function in Python. This is required
90when 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
325Extended trampoline class functionality
326=======================================
327
328The trampoline classes described in the previous sections are, by default, only
329initialized when needed. More specifically, they are initialized when a python
330class actually inherits from a registered type (instead of merely creating an
331instance of the registered type), or when a registered constructor is only
332valid for the trampoline class but not the registered class. This is primarily
333for performance reasons: when the trampoline class is not needed for anything
334except virtual method dispatching, not initializing the trampoline class
335improves performance by avoiding needing to do a run-time check to see if the
336inheriting python instance has an overloaded method.
337
338Sometimes, however, it is useful to always initialize a trampoline class as an
339intermediate class that does more than just handle virtual method dispatching.
340For example, such a class might perform extra class initialization, extra
341destruction operations, and might define new members and methods to enable a
342more python-like interface to a class.
343
344In order to tell pybind11 that it should *always* initialize the trampoline
345class when creating new instances of a type, the class constructors should be
346declared using ``py::init_alias<Args, ...>()`` instead of the usual
347``py::init<Args, ...>()``. This forces construction via the trampoline class,
348ensuring member initialization and (eventual) destruction.
349
350.. seealso::
351
Dean Moldovan0bc272b2017-06-22 23:42:11 +0200352 See the file :file:`tests/test_virtual_functions.cpp` for complete examples
Dean Moldovan67b52d82016-10-16 19:12:43 +0200353 showing both normal and forced trampoline instantiation.
354
355.. _custom_constructors:
356
357Custom constructors
358===================
359
360The syntax for binding constructors was previously introduced, but it only
361works when a constructor with the given parameters actually exists on the C++
362side. To extend this to more general cases, let's take a look at what actually
363happens under the hood: the following statement
364
365.. code-block:: cpp
366
367 py::class_<Example>(m, "Example")
368 .def(py::init<int>());
369
370is short hand notation for
371
372.. code-block:: cpp
373
374 py::class_<Example>(m, "Example")
375 .def("__init__",
376 [](Example &instance, int arg) {
377 new (&instance) Example(arg);
378 }
379 );
380
381In other words, :func:`init` creates an anonymous function that invokes an
382in-place constructor. Memory allocation etc. is already take care of beforehand
383within pybind11.
384
385.. _classes_with_non_public_destructors:
386
387Non-public destructors
388======================
389
390If a class has a private or protected destructor (as might e.g. be the case in
391a singleton pattern), a compile error will occur when creating bindings via
392pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
393is responsible for managing the lifetime of instances will reference the
394destructor even if no deallocations ever take place. In order to expose classes
395with private or protected destructors, it is possible to override the holder
396type via a holder type argument to ``class_``. Pybind11 provides a helper class
397``py::nodelete`` that disables any destructor invocations. In this case, it is
398crucial that instances are deallocated on the C++ side to avoid memory leaks.
399
400.. code-block:: cpp
401
402 /* ... definition ... */
403
404 class MyClass {
405 private:
406 ~MyClass() { }
407 };
408
409 /* ... binding code ... */
410
411 py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
myd73499b815ad2017-01-13 18:15:52 +0800412 .def(py::init<>())
Dean Moldovan67b52d82016-10-16 19:12:43 +0200413
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500414.. _implicit_conversions:
415
Dean Moldovan67b52d82016-10-16 19:12:43 +0200416Implicit conversions
417====================
418
419Suppose that instances of two types ``A`` and ``B`` are used in a project, and
420that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
421could be a fixed and an arbitrary precision number type).
422
423.. code-block:: cpp
424
425 py::class_<A>(m, "A")
426 /// ... members ...
427
428 py::class_<B>(m, "B")
429 .def(py::init<A>())
430 /// ... members ...
431
432 m.def("func",
433 [](const B &) { /* .... */ }
434 );
435
436To invoke the function ``func`` using a variable ``a`` containing an ``A``
437instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
438will automatically apply an implicit type conversion, which makes it possible
439to directly write ``func(a)``.
440
441In this situation (i.e. where ``B`` has a constructor that converts from
442``A``), the following statement enables similar implicit conversions on the
443Python side:
444
445.. code-block:: cpp
446
447 py::implicitly_convertible<A, B>();
448
449.. note::
450
451 Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
452 data type that is exposed to Python via pybind11.
453
454.. _static_properties:
455
456Static properties
457=================
458
459The section on :ref:`properties` discussed the creation of instance properties
460that are implemented in terms of C++ getters and setters.
461
462Static properties can also be created in a similar way to expose getters and
Dean Moldovandd016652017-02-16 23:02:56 +0100463setters of static class attributes. Note that the implicit ``self`` argument
464also exists in this case and is used to pass the Python ``type`` subclass
465instance. This parameter will often not be needed by the C++ side, and the
466following example illustrates how to instantiate a lambda getter function
467that ignores it:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200468
469.. code-block:: cpp
470
Dean Moldovandd016652017-02-16 23:02:56 +0100471 py::class_<Foo>(m, "Foo")
Dean Moldovan67b52d82016-10-16 19:12:43 +0200472 .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
473
474Operator overloading
475====================
476
477Suppose that we're given the following ``Vector2`` class with a vector addition
478and scalar multiplication operation, all implemented using overloaded operators
479in C++.
480
481.. code-block:: cpp
482
483 class Vector2 {
484 public:
485 Vector2(float x, float y) : x(x), y(y) { }
486
487 Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
488 Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
489 Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
490 Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
491
492 friend Vector2 operator*(float f, const Vector2 &v) {
493 return Vector2(f * v.x, f * v.y);
494 }
495
496 std::string toString() const {
497 return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
498 }
499 private:
500 float x, y;
501 };
502
503The following snippet shows how the above operators can be conveniently exposed
504to Python.
505
506.. code-block:: cpp
507
508 #include <pybind11/operators.h>
509
Dean Moldovan443ab592017-04-24 01:51:44 +0200510 PYBIND11_MODULE(example, m) {
Dean Moldovan67b52d82016-10-16 19:12:43 +0200511 py::class_<Vector2>(m, "Vector2")
512 .def(py::init<float, float>())
513 .def(py::self + py::self)
514 .def(py::self += py::self)
515 .def(py::self *= float())
516 .def(float() * py::self)
myd73499b815ad2017-01-13 18:15:52 +0800517 .def(py::self * float())
Dean Moldovan67b52d82016-10-16 19:12:43 +0200518 .def("__repr__", &Vector2::toString);
Dean Moldovan67b52d82016-10-16 19:12:43 +0200519 }
520
521Note that a line like
522
523.. code-block:: cpp
524
525 .def(py::self * float())
526
527is really just short hand notation for
528
529.. code-block:: cpp
530
531 .def("__mul__", [](const Vector2 &a, float b) {
532 return a * b;
533 }, py::is_operator())
534
535This can be useful for exposing additional operators that don't exist on the
536C++ side, or to perform other types of customization. The ``py::is_operator``
537flag marker is needed to inform pybind11 that this is an operator, which
538returns ``NotImplemented`` when invoked with incompatible arguments rather than
539throwing a type error.
540
541.. note::
542
543 To use the more convenient ``py::self`` notation, the additional
544 header file :file:`pybind11/operators.h` must be included.
545
546.. seealso::
547
548 The file :file:`tests/test_operator_overloading.cpp` contains a
549 complete example that demonstrates how to work with overloaded operators in
550 more detail.
551
552Pickling support
553================
554
555Python's ``pickle`` module provides a powerful facility to serialize and
556de-serialize a Python object graph into a binary data stream. To pickle and
557unpickle C++ classes using pybind11, two additional functions must be provided.
558Suppose the class in question has the following signature:
559
560.. code-block:: cpp
561
562 class Pickleable {
563 public:
564 Pickleable(const std::string &value) : m_value(value) { }
565 const std::string &value() const { return m_value; }
566
567 void setExtra(int extra) { m_extra = extra; }
568 int extra() const { return m_extra; }
569 private:
570 std::string m_value;
571 int m_extra = 0;
572 };
573
574The binding code including the requisite ``__setstate__`` and ``__getstate__`` methods [#f3]_
575looks as follows:
576
577.. code-block:: cpp
578
579 py::class_<Pickleable>(m, "Pickleable")
580 .def(py::init<std::string>())
581 .def("value", &Pickleable::value)
582 .def("extra", &Pickleable::extra)
583 .def("setExtra", &Pickleable::setExtra)
584 .def("__getstate__", [](const Pickleable &p) {
585 /* Return a tuple that fully encodes the state of the object */
586 return py::make_tuple(p.value(), p.extra());
587 })
588 .def("__setstate__", [](Pickleable &p, py::tuple t) {
589 if (t.size() != 2)
590 throw std::runtime_error("Invalid state!");
591
592 /* Invoke the in-place constructor. Note that this is needed even
593 when the object just has a trivial default constructor */
594 new (&p) Pickleable(t[0].cast<std::string>());
595
596 /* Assign any additional state */
597 p.setExtra(t[1].cast<int>());
598 });
599
600An instance can now be pickled as follows:
601
602.. code-block:: python
603
604 try:
605 import cPickle as pickle # Use cPickle on Python 2.7
606 except ImportError:
607 import pickle
608
609 p = Pickleable("test_value")
610 p.setExtra(15)
611 data = pickle.dumps(p, 2)
612
613Note that only the cPickle module is supported on Python 2.7. The second
614argument to ``dumps`` is also crucial: it selects the pickle protocol version
6152, since the older version 1 is not supported. Newer versions are also fine—for
616instance, specify ``-1`` to always use the latest available version. Beware:
617failure to follow these instructions will cause important pybind11 memory
618allocation routines to be skipped during unpickling, which will likely lead to
619memory corruption and/or segmentation faults.
620
621.. seealso::
622
623 The file :file:`tests/test_pickling.cpp` contains a complete example
624 that demonstrates how to pickle and unpickle types using pybind11 in more
625 detail.
626
627.. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
628
629Multiple Inheritance
630====================
631
632pybind11 can create bindings for types that derive from multiple base types
633(aka. *multiple inheritance*). To do so, specify all bases in the template
634arguments of the ``class_`` declaration:
635
636.. code-block:: cpp
637
638 py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
639 ...
640
641The base types can be specified in arbitrary order, and they can even be
642interspersed with alias types and holder types (discussed earlier in this
643document)---pybind11 will automatically find out which is which. The only
644requirement is that the first template argument is the type to be declared.
645
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500646It is also permitted to inherit multiply from exported C++ classes in Python,
647as well as inheriting from multiple Python and/or pybind-exported classes.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200648
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500649There is one caveat regarding the implementation of this feature:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200650
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500651When only one base type is specified for a C++ type that actually has multiple
652bases, pybind11 will assume that it does not participate in multiple
653inheritance, which can lead to undefined behavior. In such cases, add the tag
654``multiple_inheritance`` to the class constructor:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200655
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500656.. code-block:: cpp
Dean Moldovan67b52d82016-10-16 19:12:43 +0200657
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500658 py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
Dean Moldovan67b52d82016-10-16 19:12:43 +0200659
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500660The tag is redundant and does not need to be specified when multiple base types
661are listed.
Jason Rhinelander7437c692017-07-28 22:03:44 -0400662
663.. _module_local:
664
665Module-local class bindings
666===========================
667
668When creating a binding for a class, pybind by default makes that binding
669"global" across modules. What this means is that a type defined in one module
670can be passed to functions of other modules that expect the same C++ type. For
671example, this allows the following:
672
673.. code-block:: cpp
674
675 // In the module1.cpp binding code for module1:
676 py::class_<Pet>(m, "Pet")
677 .def(py::init<std::string>());
678
679.. code-block:: cpp
680
681 // In the module2.cpp binding code for module2:
682 m.def("pet_name", [](Pet &p) { return p.name(); });
683
684.. code-block:: pycon
685
686 >>> from module1 import Pet
687 >>> from module2 import pet_name
688 >>> mypet = Pet("Kitty")
689 >>> pet_name(mypet)
690 'Kitty'
691
692When writing binding code for a library, this is usually desirable: this
693allows, for example, splitting up a complex library into multiple Python
694modules.
695
696In some cases, however, this can cause conflicts. For example, suppose two
697unrelated modules make use of an external C++ library and each provide custom
698bindings for one of that library's classes. This will result in an error when
699a Python program attempts to import both modules (directly or indirectly)
700because of conflicting definitions on the external type:
701
702.. code-block:: cpp
703
704 // dogs.cpp
705
706 // Binding for external library class:
707 py::class<pets::Pet>(m, "Pet")
708 .def("name", &pets::Pet::name);
709
710 // Binding for local extension class:
711 py::class<Dog, pets::Pet>(m, "Dog")
712 .def(py::init<std::string>());
713
714.. code-block:: cpp
715
716 // cats.cpp, in a completely separate project from the above dogs.cpp.
717
718 // Binding for external library class:
719 py::class<pets::Pet>(m, "Pet")
720 .def("get_name", &pets::Pet::name);
721
722 // Binding for local extending class:
723 py::class<Cat, pets::Pet>(m, "Cat")
724 .def(py::init<std::string>());
725
726.. code-block:: pycon
727
728 >>> import cats
729 >>> import dogs
730 Traceback (most recent call last):
731 File "<stdin>", line 1, in <module>
732 ImportError: generic_type: type "Pet" is already registered!
733
734To get around this, you can tell pybind11 to keep the external class binding
735localized to the module by passing the ``py::module_local()`` attribute into
736the ``py::class_`` constructor:
737
738.. code-block:: cpp
739
740 // Pet binding in dogs.cpp:
741 py::class<pets::Pet>(m, "Pet", py::module_local())
742 .def("name", &pets::Pet::name);
743
744.. code-block:: cpp
745
746 // Pet binding in cats.cpp:
747 py::class<pets::Pet>(m, "Pet", py::module_local())
748 .def("get_name", &pets::Pet::name);
749
750This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes
751that can only be accepted as ``Pet`` arguments within those classes. This
752avoids the conflict and allows both modules to be loaded.
753
754One limitation of this approach is that because ``py::module_local`` types are
755distinct on the Python side, it is not possible to pass such a module-local
756type as a C++ ``Pet``-taking function outside that module. For example, if the
757above ``cats`` and ``dogs`` module are each extended with a function:
758
759.. code-block:: cpp
760
761 m.def("petname", [](pets::Pet &p) { return p.name(); });
762
763you will only be able to call the function with the local module's class:
764
765.. code-block:: pycon
766
767 >>> import cats, dogs # No error because of the added py::module_local()
768 >>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover")
769 >>> (cats.petname(mycat), dogs.petname(mydog))
770 ('Fluffy', 'Rover')
771 >>> cats.petname(mydog)
772 Traceback (most recent call last):
773 File "<stdin>", line 1, in <module>
774 TypeError: petname(): incompatible function arguments. The following argument types are supported:
775 1. (arg0: cats.Pet) -> str
776
777 Invoked with: <dogs.Dog object at 0x123>
778
Jason Rhinelander4b159232017-08-04 13:05:12 -0400779It is possible to use ``py::module_local()`` registrations in one module even if another module
780registers the same type globally: within the module with the module-local definition, all C++
781instances will be cast to the associated bound Python type. Outside the module, any such values
782are converted to the global Python type created elsewhere.
783
Jason Rhinelander7437c692017-07-28 22:03:44 -0400784.. note::
785
786 STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`
787 header) apply ``py::module_local`` by default when the bound type might
788 conflict with other modules; see :ref:`stl_bind` for details.
789
790.. note::
791
792 The localization of the bound types is actually tied to the shared object
793 or binary generated by the compiler/linker. For typical modules created
794 with ``PYBIND11_MODULE()``, this distinction is not significant. It is
795 possible, however, when :ref:`embedding` to embed multiple modules in the
796 same binary (see :ref:`embedding_modules`). In such a case, the
797 localization will apply across all embedded modules within the same binary.
798
799.. seealso::
800
801 The file :file:`tests/test_local_bindings.cpp` contains additional examples
802 that demonstrate how ``py::module_local()`` works.