classes.rst 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. Classes
  2. #######
  3. This section presents advanced binding code for classes and it is assumed
  4. that you are already familiar with the basics from :doc:`/classes`.
  5. .. _overriding_virtuals:
  6. Overriding virtual functions in Python
  7. ======================================
  8. Suppose that a C++ class or interface has a virtual function that we'd like to
  9. to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is
  10. given as a specific example of how one would do this with traditional C++
  11. code).
  12. .. code-block:: cpp
  13. class Animal {
  14. public:
  15. virtual ~Animal() { }
  16. virtual std::string go(int n_times) = 0;
  17. };
  18. class Dog : public Animal {
  19. public:
  20. std::string go(int n_times) override {
  21. std::string result;
  22. for (int i=0; i<n_times; ++i)
  23. result += "woof! ";
  24. return result;
  25. }
  26. };
  27. Let's also suppose that we are given a plain function which calls the
  28. function ``go()`` on an arbitrary ``Animal`` instance.
  29. .. code-block:: cpp
  30. std::string call_go(Animal *animal) {
  31. return animal->go(3);
  32. }
  33. Normally, the binding code for these classes would look as follows:
  34. .. code-block:: cpp
  35. PYBIND11_MODULE(example, m) {
  36. py::class_<Animal> animal(m, "Animal");
  37. animal
  38. .def("go", &Animal::go);
  39. py::class_<Dog>(m, "Dog", animal)
  40. .def(py::init<>());
  41. m.def("call_go", &call_go);
  42. }
  43. However, these bindings are impossible to extend: ``Animal`` is not
  44. constructible, and we clearly require some kind of "trampoline" that
  45. redirects virtual calls back to Python.
  46. Defining a new type of ``Animal`` from within Python is possible but requires a
  47. helper class that is defined as follows:
  48. .. code-block:: cpp
  49. class PyAnimal : public Animal {
  50. public:
  51. /* Inherit the constructors */
  52. using Animal::Animal;
  53. /* Trampoline (need one for each virtual function) */
  54. std::string go(int n_times) override {
  55. PYBIND11_OVERLOAD_PURE(
  56. std::string, /* Return type */
  57. Animal, /* Parent class */
  58. go, /* Name of function in C++ (must match Python name) */
  59. n_times /* Argument(s) */
  60. );
  61. }
  62. };
  63. The macro :func:`PYBIND11_OVERLOAD_PURE` should be used for pure virtual
  64. functions, and :func:`PYBIND11_OVERLOAD` should be used for functions which have
  65. a default implementation. There are also two alternate macros
  66. :func:`PYBIND11_OVERLOAD_PURE_NAME` and :func:`PYBIND11_OVERLOAD_NAME` which
  67. take a string-valued name argument between the *Parent class* and *Name of the
  68. function* slots, which defines the name of function in Python. This is required
  69. when the C++ and Python versions of the
  70. function have different names, e.g. ``operator()`` vs ``__call__``.
  71. The binding code also needs a few minor adaptations (highlighted):
  72. .. code-block:: cpp
  73. :emphasize-lines: 2,4,5
  74. PYBIND11_MODULE(example, m) {
  75. py::class_<Animal, PyAnimal /* <--- trampoline*/> animal(m, "Animal");
  76. animal
  77. .def(py::init<>())
  78. .def("go", &Animal::go);
  79. py::class_<Dog>(m, "Dog", animal)
  80. .def(py::init<>());
  81. m.def("call_go", &call_go);
  82. }
  83. Importantly, pybind11 is made aware of the trampoline helper class by
  84. specifying it as an extra template argument to :class:`class_`. (This can also
  85. be combined with other template arguments such as a custom holder type; the
  86. order of template types does not matter). Following this, we are able to
  87. define a constructor as usual.
  88. Bindings should be made against the actual class, not the trampoline helper class.
  89. .. code-block:: cpp
  90. py::class_<Animal, PyAnimal /* <--- trampoline*/> animal(m, "Animal");
  91. animal
  92. .def(py::init<>())
  93. .def("go", &PyAnimal::go); /* <--- THIS IS WRONG, use &Animal::go */
  94. Note, however, that the above is sufficient for allowing python classes to
  95. extend ``Animal``, but not ``Dog``: see :ref:`virtual_and_inheritance` for the
  96. necessary steps required to providing proper overload support for inherited
  97. classes.
  98. The Python session below shows how to override ``Animal::go`` and invoke it via
  99. a virtual method call.
  100. .. code-block:: pycon
  101. >>> from example import *
  102. >>> d = Dog()
  103. >>> call_go(d)
  104. u'woof! woof! woof! '
  105. >>> class Cat(Animal):
  106. ... def go(self, n_times):
  107. ... return "meow! " * n_times
  108. ...
  109. >>> c = Cat()
  110. >>> call_go(c)
  111. u'meow! meow! meow! '
  112. If you are defining a custom constructor in a derived Python class, you *must*
  113. ensure that you explicitly call the bound C++ constructor using ``__init__``,
  114. *regardless* of whether it is a default constructor or not. Otherwise, the
  115. memory for the C++ portion of the instance will be left uninitialized, which
  116. will generally leave the C++ instance in an invalid state and cause undefined
  117. behavior if the C++ instance is subsequently used.
  118. Here is an example:
  119. .. code-block:: python
  120. class Dachschund(Dog):
  121. def __init__(self, name):
  122. Dog.__init__(self) # Without this, undefind behavior may occur if the C++ portions are referenced.
  123. self.name = name
  124. def bark(self):
  125. return "yap!"
  126. Note that a direct ``__init__`` constructor *should be called*, and ``super()``
  127. should not be used. For simple cases of linear inheritance, ``super()``
  128. may work, but once you begin mixing Python and C++ multiple inheritance,
  129. things will fall apart due to differences between Python's MRO and C++'s
  130. mechanisms.
  131. Please take a look at the :ref:`macro_notes` before using this feature.
  132. .. note::
  133. When the overridden type returns a reference or pointer to a type that
  134. pybind11 converts from Python (for example, numeric values, std::string,
  135. and other built-in value-converting types), there are some limitations to
  136. be aware of:
  137. - because in these cases there is no C++ variable to reference (the value
  138. is stored in the referenced Python variable), pybind11 provides one in
  139. the PYBIND11_OVERLOAD macros (when needed) with static storage duration.
  140. Note that this means that invoking the overloaded method on *any*
  141. instance will change the referenced value stored in *all* instances of
  142. that type.
  143. - Attempts to modify a non-const reference will not have the desired
  144. effect: it will change only the static cache variable, but this change
  145. will not propagate to underlying Python instance, and the change will be
  146. replaced the next time the overload is invoked.
  147. .. seealso::
  148. The file :file:`tests/test_virtual_functions.cpp` contains a complete
  149. example that demonstrates how to override virtual functions using pybind11
  150. in more detail.
  151. .. _virtual_and_inheritance:
  152. Combining virtual functions and inheritance
  153. ===========================================
  154. When combining virtual methods with inheritance, you need to be sure to provide
  155. an override for each method for which you want to allow overrides from derived
  156. python classes. For example, suppose we extend the above ``Animal``/``Dog``
  157. example as follows:
  158. .. code-block:: cpp
  159. class Animal {
  160. public:
  161. virtual std::string go(int n_times) = 0;
  162. virtual std::string name() { return "unknown"; }
  163. };
  164. class Dog : public Animal {
  165. public:
  166. std::string go(int n_times) override {
  167. std::string result;
  168. for (int i=0; i<n_times; ++i)
  169. result += bark() + " ";
  170. return result;
  171. }
  172. virtual std::string bark() { return "woof!"; }
  173. };
  174. then the trampoline class for ``Animal`` must, as described in the previous
  175. section, override ``go()`` and ``name()``, but in order to allow python code to
  176. inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
  177. overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
  178. methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
  179. override the ``name()`` method):
  180. .. code-block:: cpp
  181. class PyAnimal : public Animal {
  182. public:
  183. using Animal::Animal; // Inherit constructors
  184. std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Animal, go, n_times); }
  185. std::string name() override { PYBIND11_OVERLOAD(std::string, Animal, name, ); }
  186. };
  187. class PyDog : public Dog {
  188. public:
  189. using Dog::Dog; // Inherit constructors
  190. std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Dog, go, n_times); }
  191. std::string name() override { PYBIND11_OVERLOAD(std::string, Dog, name, ); }
  192. std::string bark() override { PYBIND11_OVERLOAD(std::string, Dog, bark, ); }
  193. };
  194. .. note::
  195. Note the trailing commas in the ``PYBIND11_OVERLOAD`` calls to ``name()``
  196. and ``bark()``. These are needed to portably implement a trampoline for a
  197. function that does not take any arguments. For functions that take
  198. a nonzero number of arguments, the trailing comma must be omitted.
  199. A registered class derived from a pybind11-registered class with virtual
  200. methods requires a similar trampoline class, *even if* it doesn't explicitly
  201. declare or override any virtual methods itself:
  202. .. code-block:: cpp
  203. class Husky : public Dog {};
  204. class PyHusky : public Husky {
  205. public:
  206. using Husky::Husky; // Inherit constructors
  207. std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Husky, go, n_times); }
  208. std::string name() override { PYBIND11_OVERLOAD(std::string, Husky, name, ); }
  209. std::string bark() override { PYBIND11_OVERLOAD(std::string, Husky, bark, ); }
  210. };
  211. There is, however, a technique that can be used to avoid this duplication
  212. (which can be especially helpful for a base class with several virtual
  213. methods). The technique involves using template trampoline classes, as
  214. follows:
  215. .. code-block:: cpp
  216. template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
  217. public:
  218. using AnimalBase::AnimalBase; // Inherit constructors
  219. std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, AnimalBase, go, n_times); }
  220. std::string name() override { PYBIND11_OVERLOAD(std::string, AnimalBase, name, ); }
  221. };
  222. template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
  223. public:
  224. using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
  225. // Override PyAnimal's pure virtual go() with a non-pure one:
  226. std::string go(int n_times) override { PYBIND11_OVERLOAD(std::string, DogBase, go, n_times); }
  227. std::string bark() override { PYBIND11_OVERLOAD(std::string, DogBase, bark, ); }
  228. };
  229. This technique has the advantage of requiring just one trampoline method to be
  230. declared per virtual method and pure virtual method override. It does,
  231. however, require the compiler to generate at least as many methods (and
  232. possibly more, if both pure virtual and overridden pure virtual methods are
  233. exposed, as above).
  234. The classes are then registered with pybind11 using:
  235. .. code-block:: cpp
  236. py::class_<Animal, PyAnimal<>> animal(m, "Animal");
  237. py::class_<Dog, PyDog<>> dog(m, "Dog");
  238. py::class_<Husky, PyDog<Husky>> husky(m, "Husky");
  239. // ... add animal, dog, husky definitions
  240. Note that ``Husky`` did not require a dedicated trampoline template class at
  241. all, since it neither declares any new virtual methods nor provides any pure
  242. virtual method implementations.
  243. With either the repeated-virtuals or templated trampoline methods in place, you
  244. can now create a python class that inherits from ``Dog``:
  245. .. code-block:: python
  246. class ShihTzu(Dog):
  247. def bark(self):
  248. return "yip!"
  249. .. seealso::
  250. See the file :file:`tests/test_virtual_functions.cpp` for complete examples
  251. using both the duplication and templated trampoline approaches.
  252. .. _extended_aliases:
  253. Extended trampoline class functionality
  254. =======================================
  255. The trampoline classes described in the previous sections are, by default, only
  256. initialized when needed. More specifically, they are initialized when a python
  257. class actually inherits from a registered type (instead of merely creating an
  258. instance of the registered type), or when a registered constructor is only
  259. valid for the trampoline class but not the registered class. This is primarily
  260. for performance reasons: when the trampoline class is not needed for anything
  261. except virtual method dispatching, not initializing the trampoline class
  262. improves performance by avoiding needing to do a run-time check to see if the
  263. inheriting python instance has an overloaded method.
  264. Sometimes, however, it is useful to always initialize a trampoline class as an
  265. intermediate class that does more than just handle virtual method dispatching.
  266. For example, such a class might perform extra class initialization, extra
  267. destruction operations, and might define new members and methods to enable a
  268. more python-like interface to a class.
  269. In order to tell pybind11 that it should *always* initialize the trampoline
  270. class when creating new instances of a type, the class constructors should be
  271. declared using ``py::init_alias<Args, ...>()`` instead of the usual
  272. ``py::init<Args, ...>()``. This forces construction via the trampoline class,
  273. ensuring member initialization and (eventual) destruction.
  274. .. seealso::
  275. See the file :file:`tests/test_virtual_functions.cpp` for complete examples
  276. showing both normal and forced trampoline instantiation.
  277. .. _custom_constructors:
  278. Custom constructors
  279. ===================
  280. The syntax for binding constructors was previously introduced, but it only
  281. works when a constructor of the appropriate arguments actually exists on the
  282. C++ side. To extend this to more general cases, pybind11 makes it possible
  283. to bind factory functions as constructors. For example, suppose you have a
  284. class like this:
  285. .. code-block:: cpp
  286. class Example {
  287. private:
  288. Example(int); // private constructor
  289. public:
  290. // Factory function:
  291. static Example create(int a) { return Example(a); }
  292. };
  293. py::class_<Example>(m, "Example")
  294. .def(py::init(&Example::create));
  295. While it is possible to create a straightforward binding of the static
  296. ``create`` method, it may sometimes be preferable to expose it as a constructor
  297. on the Python side. This can be accomplished by calling ``.def(py::init(...))``
  298. with the function reference returning the new instance passed as an argument.
  299. It is also possible to use this approach to bind a function returning a new
  300. instance by raw pointer or by the holder (e.g. ``std::unique_ptr``).
  301. The following example shows the different approaches:
  302. .. code-block:: cpp
  303. class Example {
  304. private:
  305. Example(int); // private constructor
  306. public:
  307. // Factory function - returned by value:
  308. static Example create(int a) { return Example(a); }
  309. // These constructors are publicly callable:
  310. Example(double);
  311. Example(int, int);
  312. Example(std::string);
  313. };
  314. py::class_<Example>(m, "Example")
  315. // Bind the factory function as a constructor:
  316. .def(py::init(&Example::create))
  317. // Bind a lambda function returning a pointer wrapped in a holder:
  318. .def(py::init([](std::string arg) {
  319. return std::unique_ptr<Example>(new Example(arg));
  320. }))
  321. // Return a raw pointer:
  322. .def(py::init([](int a, int b) { return new Example(a, b); }))
  323. // You can mix the above with regular C++ constructor bindings as well:
  324. .def(py::init<double>())
  325. ;
  326. When the constructor is invoked from Python, pybind11 will call the factory
  327. function and store the resulting C++ instance in the Python instance.
  328. When combining factory functions constructors with :ref:`virtual function
  329. trampolines <overriding_virtuals>` there are two approaches. The first is to
  330. add a constructor to the alias class that takes a base value by
  331. rvalue-reference. If such a constructor is available, it will be used to
  332. construct an alias instance from the value returned by the factory function.
  333. The second option is to provide two factory functions to ``py::init()``: the
  334. first will be invoked when no alias class is required (i.e. when the class is
  335. being used but not inherited from in Python), and the second will be invoked
  336. when an alias is required.
  337. You can also specify a single factory function that always returns an alias
  338. instance: this will result in behaviour similar to ``py::init_alias<...>()``,
  339. as described in the :ref:`extended trampoline class documentation
  340. <extended_aliases>`.
  341. The following example shows the different factory approaches for a class with
  342. an alias:
  343. .. code-block:: cpp
  344. #include <pybind11/factory.h>
  345. class Example {
  346. public:
  347. // ...
  348. virtual ~Example() = default;
  349. };
  350. class PyExample : public Example {
  351. public:
  352. using Example::Example;
  353. PyExample(Example &&base) : Example(std::move(base)) {}
  354. };
  355. py::class_<Example, PyExample>(m, "Example")
  356. // Returns an Example pointer. If a PyExample is needed, the Example
  357. // instance will be moved via the extra constructor in PyExample, above.
  358. .def(py::init([]() { return new Example(); }))
  359. // Two callbacks:
  360. .def(py::init([]() { return new Example(); } /* no alias needed */,
  361. []() { return new PyExample(); } /* alias needed */))
  362. // *Always* returns an alias instance (like py::init_alias<>())
  363. .def(py::init([]() { return new PyExample(); }))
  364. ;
  365. Brace initialization
  366. --------------------
  367. ``pybind11::init<>`` internally uses C++11 brace initialization to call the
  368. constructor of the target class. This means that it can be used to bind
  369. *implicit* constructors as well:
  370. .. code-block:: cpp
  371. struct Aggregate {
  372. int a;
  373. std::string b;
  374. };
  375. py::class_<Aggregate>(m, "Aggregate")
  376. .def(py::init<int, const std::string &>());
  377. .. note::
  378. Note that brace initialization preferentially invokes constructor overloads
  379. taking a ``std::initializer_list``. In the rare event that this causes an
  380. issue, you can work around it by using ``py::init(...)`` with a lambda
  381. function that constructs the new object as desired.
  382. .. _classes_with_non_public_destructors:
  383. Non-public destructors
  384. ======================
  385. If a class has a private or protected destructor (as might e.g. be the case in
  386. a singleton pattern), a compile error will occur when creating bindings via
  387. pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
  388. is responsible for managing the lifetime of instances will reference the
  389. destructor even if no deallocations ever take place. In order to expose classes
  390. with private or protected destructors, it is possible to override the holder
  391. type via a holder type argument to ``class_``. Pybind11 provides a helper class
  392. ``py::nodelete`` that disables any destructor invocations. In this case, it is
  393. crucial that instances are deallocated on the C++ side to avoid memory leaks.
  394. .. code-block:: cpp
  395. /* ... definition ... */
  396. class MyClass {
  397. private:
  398. ~MyClass() { }
  399. };
  400. /* ... binding code ... */
  401. py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
  402. .def(py::init<>())
  403. .. _implicit_conversions:
  404. Implicit conversions
  405. ====================
  406. Suppose that instances of two types ``A`` and ``B`` are used in a project, and
  407. that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
  408. could be a fixed and an arbitrary precision number type).
  409. .. code-block:: cpp
  410. py::class_<A>(m, "A")
  411. /// ... members ...
  412. py::class_<B>(m, "B")
  413. .def(py::init<A>())
  414. /// ... members ...
  415. m.def("func",
  416. [](const B &) { /* .... */ }
  417. );
  418. To invoke the function ``func`` using a variable ``a`` containing an ``A``
  419. instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
  420. will automatically apply an implicit type conversion, which makes it possible
  421. to directly write ``func(a)``.
  422. In this situation (i.e. where ``B`` has a constructor that converts from
  423. ``A``), the following statement enables similar implicit conversions on the
  424. Python side:
  425. .. code-block:: cpp
  426. py::implicitly_convertible<A, B>();
  427. .. note::
  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. To prevent runaway recursion, implicit conversions are non-reentrant: an
  431. implicit conversion invoked as part of another implicit conversion of the
  432. same type (i.e. from ``A`` to ``B``) will fail.
  433. .. _static_properties:
  434. Static properties
  435. =================
  436. The section on :ref:`properties` discussed the creation of instance properties
  437. that are implemented in terms of C++ getters and setters.
  438. Static properties can also be created in a similar way to expose getters and
  439. setters of static class attributes. Note that the implicit ``self`` argument
  440. also exists in this case and is used to pass the Python ``type`` subclass
  441. instance. This parameter will often not be needed by the C++ side, and the
  442. following example illustrates how to instantiate a lambda getter function
  443. that ignores it:
  444. .. code-block:: cpp
  445. py::class_<Foo>(m, "Foo")
  446. .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
  447. Operator overloading
  448. ====================
  449. Suppose that we're given the following ``Vector2`` class with a vector addition
  450. and scalar multiplication operation, all implemented using overloaded operators
  451. in C++.
  452. .. code-block:: cpp
  453. class Vector2 {
  454. public:
  455. Vector2(float x, float y) : x(x), y(y) { }
  456. Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
  457. Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
  458. Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
  459. Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
  460. friend Vector2 operator*(float f, const Vector2 &v) {
  461. return Vector2(f * v.x, f * v.y);
  462. }
  463. std::string toString() const {
  464. return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
  465. }
  466. private:
  467. float x, y;
  468. };
  469. The following snippet shows how the above operators can be conveniently exposed
  470. to Python.
  471. .. code-block:: cpp
  472. #include <pybind11/operators.h>
  473. PYBIND11_MODULE(example, m) {
  474. py::class_<Vector2>(m, "Vector2")
  475. .def(py::init<float, float>())
  476. .def(py::self + py::self)
  477. .def(py::self += py::self)
  478. .def(py::self *= float())
  479. .def(float() * py::self)
  480. .def(py::self * float())
  481. .def("__repr__", &Vector2::toString);
  482. }
  483. Note that a line like
  484. .. code-block:: cpp
  485. .def(py::self * float())
  486. is really just short hand notation for
  487. .. code-block:: cpp
  488. .def("__mul__", [](const Vector2 &a, float b) {
  489. return a * b;
  490. }, py::is_operator())
  491. This can be useful for exposing additional operators that don't exist on the
  492. C++ side, or to perform other types of customization. The ``py::is_operator``
  493. flag marker is needed to inform pybind11 that this is an operator, which
  494. returns ``NotImplemented`` when invoked with incompatible arguments rather than
  495. throwing a type error.
  496. .. note::
  497. To use the more convenient ``py::self`` notation, the additional
  498. header file :file:`pybind11/operators.h` must be included.
  499. .. seealso::
  500. The file :file:`tests/test_operator_overloading.cpp` contains a
  501. complete example that demonstrates how to work with overloaded operators in
  502. more detail.
  503. .. _pickling:
  504. Pickling support
  505. ================
  506. Python's ``pickle`` module provides a powerful facility to serialize and
  507. de-serialize a Python object graph into a binary data stream. To pickle and
  508. unpickle C++ classes using pybind11, a ``py::pickle()`` definition must be
  509. provided. Suppose the class in question has the following signature:
  510. .. code-block:: cpp
  511. class Pickleable {
  512. public:
  513. Pickleable(const std::string &value) : m_value(value) { }
  514. const std::string &value() const { return m_value; }
  515. void setExtra(int extra) { m_extra = extra; }
  516. int extra() const { return m_extra; }
  517. private:
  518. std::string m_value;
  519. int m_extra = 0;
  520. };
  521. Pickling support in Python is enabled by defining the ``__setstate__`` and
  522. ``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()``
  523. to bind these two functions:
  524. .. code-block:: cpp
  525. py::class_<Pickleable>(m, "Pickleable")
  526. .def(py::init<std::string>())
  527. .def("value", &Pickleable::value)
  528. .def("extra", &Pickleable::extra)
  529. .def("setExtra", &Pickleable::setExtra)
  530. .def(py::pickle(
  531. [](const Pickleable &p) { // __getstate__
  532. /* Return a tuple that fully encodes the state of the object */
  533. return py::make_tuple(p.value(), p.extra());
  534. },
  535. [](py::tuple t) { // __setstate__
  536. if (t.size() != 2)
  537. throw std::runtime_error("Invalid state!");
  538. /* Create a new C++ instance */
  539. Pickleable p(t[0].cast<std::string>());
  540. /* Assign any additional state */
  541. p.setExtra(t[1].cast<int>());
  542. return p;
  543. }
  544. ));
  545. The ``__setstate__`` part of the ``py::picke()`` definition follows the same
  546. rules as the single-argument version of ``py::init()``. The return type can be
  547. a value, pointer or holder type. See :ref:`custom_constructors` for details.
  548. An instance can now be pickled as follows:
  549. .. code-block:: python
  550. try:
  551. import cPickle as pickle # Use cPickle on Python 2.7
  552. except ImportError:
  553. import pickle
  554. p = Pickleable("test_value")
  555. p.setExtra(15)
  556. data = pickle.dumps(p, 2)
  557. Note that only the cPickle module is supported on Python 2.7. The second
  558. argument to ``dumps`` is also crucial: it selects the pickle protocol version
  559. 2, since the older version 1 is not supported. Newer versions are also fine—for
  560. instance, specify ``-1`` to always use the latest available version. Beware:
  561. failure to follow these instructions will cause important pybind11 memory
  562. allocation routines to be skipped during unpickling, which will likely lead to
  563. memory corruption and/or segmentation faults.
  564. .. seealso::
  565. The file :file:`tests/test_pickling.cpp` contains a complete example
  566. that demonstrates how to pickle and unpickle types using pybind11 in more
  567. detail.
  568. .. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
  569. Multiple Inheritance
  570. ====================
  571. pybind11 can create bindings for types that derive from multiple base types
  572. (aka. *multiple inheritance*). To do so, specify all bases in the template
  573. arguments of the ``class_`` declaration:
  574. .. code-block:: cpp
  575. py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
  576. ...
  577. The base types can be specified in arbitrary order, and they can even be
  578. interspersed with alias types and holder types (discussed earlier in this
  579. document)---pybind11 will automatically find out which is which. The only
  580. requirement is that the first template argument is the type to be declared.
  581. It is also permitted to inherit multiply from exported C++ classes in Python,
  582. as well as inheriting from multiple Python and/or pybind-exported classes.
  583. There is one caveat regarding the implementation of this feature:
  584. When only one base type is specified for a C++ type that actually has multiple
  585. bases, pybind11 will assume that it does not participate in multiple
  586. inheritance, which can lead to undefined behavior. In such cases, add the tag
  587. ``multiple_inheritance`` to the class constructor:
  588. .. code-block:: cpp
  589. py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
  590. The tag is redundant and does not need to be specified when multiple base types
  591. are listed.
  592. .. _module_local:
  593. Module-local class bindings
  594. ===========================
  595. When creating a binding for a class, pybind by default makes that binding
  596. "global" across modules. What this means is that a type defined in one module
  597. can be returned from any module resulting in the same Python type. For
  598. example, this allows the following:
  599. .. code-block:: cpp
  600. // In the module1.cpp binding code for module1:
  601. py::class_<Pet>(m, "Pet")
  602. .def(py::init<std::string>())
  603. .def_readonly("name", &Pet::name);
  604. .. code-block:: cpp
  605. // In the module2.cpp binding code for module2:
  606. m.def("create_pet", [](std::string name) { return new Pet(name); });
  607. .. code-block:: pycon
  608. >>> from module1 import Pet
  609. >>> from module2 import create_pet
  610. >>> pet1 = Pet("Kitty")
  611. >>> pet2 = create_pet("Doggy")
  612. >>> pet2.name()
  613. 'Doggy'
  614. When writing binding code for a library, this is usually desirable: this
  615. allows, for example, splitting up a complex library into multiple Python
  616. modules.
  617. In some cases, however, this can cause conflicts. For example, suppose two
  618. unrelated modules make use of an external C++ library and each provide custom
  619. bindings for one of that library's classes. This will result in an error when
  620. a Python program attempts to import both modules (directly or indirectly)
  621. because of conflicting definitions on the external type:
  622. .. code-block:: cpp
  623. // dogs.cpp
  624. // Binding for external library class:
  625. py::class<pets::Pet>(m, "Pet")
  626. .def("name", &pets::Pet::name);
  627. // Binding for local extension class:
  628. py::class<Dog, pets::Pet>(m, "Dog")
  629. .def(py::init<std::string>());
  630. .. code-block:: cpp
  631. // cats.cpp, in a completely separate project from the above dogs.cpp.
  632. // Binding for external library class:
  633. py::class<pets::Pet>(m, "Pet")
  634. .def("get_name", &pets::Pet::name);
  635. // Binding for local extending class:
  636. py::class<Cat, pets::Pet>(m, "Cat")
  637. .def(py::init<std::string>());
  638. .. code-block:: pycon
  639. >>> import cats
  640. >>> import dogs
  641. Traceback (most recent call last):
  642. File "<stdin>", line 1, in <module>
  643. ImportError: generic_type: type "Pet" is already registered!
  644. To get around this, you can tell pybind11 to keep the external class binding
  645. localized to the module by passing the ``py::module_local()`` attribute into
  646. the ``py::class_`` constructor:
  647. .. code-block:: cpp
  648. // Pet binding in dogs.cpp:
  649. py::class<pets::Pet>(m, "Pet", py::module_local())
  650. .def("name", &pets::Pet::name);
  651. .. code-block:: cpp
  652. // Pet binding in cats.cpp:
  653. py::class<pets::Pet>(m, "Pet", py::module_local())
  654. .def("get_name", &pets::Pet::name);
  655. This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes,
  656. avoiding the conflict and allowing both modules to be loaded. C++ code in the
  657. ``dogs`` module that casts or returns a ``Pet`` instance will result in a
  658. ``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result
  659. in a ``cats.Pet`` Python instance.
  660. This does come with two caveats, however: First, external modules cannot return
  661. or cast a ``Pet`` instance to Python (unless they also provide their own local
  662. bindings). Second, from the Python point of view they are two distinct classes.
  663. Note that the locality only applies in the C++ -> Python direction. When
  664. passing such a ``py::module_local`` type into a C++ function, the module-local
  665. classes are still considered. This means that if the following function is
  666. added to any module (including but not limited to the ``cats`` and ``dogs``
  667. modules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet``
  668. argument:
  669. .. code-block:: cpp
  670. m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); });
  671. For example, suppose the above function is added to each of ``cats.cpp``,
  672. ``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that
  673. does *not* bind ``Pets`` at all).
  674. .. code-block:: pycon
  675. >>> import cats, dogs, frogs # No error because of the added py::module_local()
  676. >>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover")
  677. >>> (cats.pet_name(mycat), dogs.pet_name(mydog))
  678. ('Fluffy', 'Rover')
  679. >>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat))
  680. ('Rover', 'Fluffy', 'Fluffy')
  681. It is possible to use ``py::module_local()`` registrations in one module even
  682. if another module registers the same type globally: within the module with the
  683. module-local definition, all C++ instances will be cast to the associated bound
  684. Python type. In other modules any such values are converted to the global
  685. Python type created elsewhere.
  686. .. note::
  687. STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`
  688. header) apply ``py::module_local`` by default when the bound type might
  689. conflict with other modules; see :ref:`stl_bind` for details.
  690. .. note::
  691. The localization of the bound types is actually tied to the shared object
  692. or binary generated by the compiler/linker. For typical modules created
  693. with ``PYBIND11_MODULE()``, this distinction is not significant. It is
  694. possible, however, when :ref:`embedding` to embed multiple modules in the
  695. same binary (see :ref:`embedding_modules`). In such a case, the
  696. localization will apply across all embedded modules within the same binary.
  697. .. seealso::
  698. The file :file:`tests/test_local_bindings.cpp` contains additional examples
  699. that demonstrate how ``py::module_local()`` works.
  700. Binding protected member functions
  701. ==================================
  702. It's normally not possible to expose ``protected`` member functions to Python:
  703. .. code-block:: cpp
  704. class A {
  705. protected:
  706. int foo() const { return 42; }
  707. };
  708. py::class_<A>(m, "A")
  709. .def("foo", &A::foo); // error: 'foo' is a protected member of 'A'
  710. On one hand, this is good because non-``public`` members aren't meant to be
  711. accessed from the outside. But we may want to make use of ``protected``
  712. functions in derived Python classes.
  713. The following pattern makes this possible:
  714. .. code-block:: cpp
  715. class A {
  716. protected:
  717. int foo() const { return 42; }
  718. };
  719. class Publicist : public A { // helper type for exposing protected functions
  720. public:
  721. using A::foo; // inherited with different access modifier
  722. };
  723. py::class_<A>(m, "A") // bind the primary class
  724. .def("foo", &Publicist::foo); // expose protected methods via the publicist
  725. This works because ``&Publicist::foo`` is exactly the same function as
  726. ``&A::foo`` (same signature and address), just with a different access
  727. modifier. The only purpose of the ``Publicist`` helper class is to make
  728. the function name ``public``.
  729. If the intent is to expose ``protected`` ``virtual`` functions which can be
  730. overridden in Python, the publicist pattern can be combined with the previously
  731. described trampoline:
  732. .. code-block:: cpp
  733. class A {
  734. public:
  735. virtual ~A() = default;
  736. protected:
  737. virtual int foo() const { return 42; }
  738. };
  739. class Trampoline : public A {
  740. public:
  741. int foo() const override { PYBIND11_OVERLOAD(int, A, foo, ); }
  742. };
  743. class Publicist : public A {
  744. public:
  745. using A::foo;
  746. };
  747. py::class_<A, Trampoline>(m, "A") // <-- `Trampoline` here
  748. .def("foo", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`!
  749. .. note::
  750. MSVC 2015 has a compiler bug (fixed in version 2017) which
  751. requires a more explicit function binding in the form of
  752. ``.def("foo", static_cast<int (A::*)() const>(&Publicist::foo));``
  753. where ``int (A::*)() const`` is the type of ``A::foo``.