classes.rst 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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>(m, "Animal")
  37. .def("go", &Animal::go);
  38. py::class_<Dog, Animal>(m, "Dog")
  39. .def(py::init<>());
  40. m.def("call_go", &call_go);
  41. }
  42. However, these bindings are impossible to extend: ``Animal`` is not
  43. constructible, and we clearly require some kind of "trampoline" that
  44. redirects virtual calls back to Python.
  45. Defining a new type of ``Animal`` from within Python is possible but requires a
  46. helper class that is defined as follows:
  47. .. code-block:: cpp
  48. class PyAnimal : public Animal {
  49. public:
  50. /* Inherit the constructors */
  51. using Animal::Animal;
  52. /* Trampoline (need one for each virtual function) */
  53. std::string go(int n_times) override {
  54. PYBIND11_OVERRIDE_PURE(
  55. std::string, /* Return type */
  56. Animal, /* Parent class */
  57. go, /* Name of function in C++ (must match Python name) */
  58. n_times /* Argument(s) */
  59. );
  60. }
  61. };
  62. The macro :c:macro:`PYBIND11_OVERRIDE_PURE` should be used for pure virtual
  63. functions, and :c:macro:`PYBIND11_OVERRIDE` should be used for functions which have
  64. a default implementation. There are also two alternate macros
  65. :c:macro:`PYBIND11_OVERRIDE_PURE_NAME` and :c:macro:`PYBIND11_OVERRIDE_NAME` which
  66. take a string-valued name argument between the *Parent class* and *Name of the
  67. function* slots, which defines the name of function in Python. This is required
  68. when the C++ and Python versions of the
  69. function have different names, e.g. ``operator()`` vs ``__call__``.
  70. The binding code also needs a few minor adaptations (highlighted):
  71. .. code-block:: cpp
  72. :emphasize-lines: 2,3
  73. PYBIND11_MODULE(example, m) {
  74. py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal")
  75. .def(py::init<>())
  76. .def("go", &Animal::go);
  77. py::class_<Dog, Animal>(m, "Dog")
  78. .def(py::init<>());
  79. m.def("call_go", &call_go);
  80. }
  81. Importantly, pybind11 is made aware of the trampoline helper class by
  82. specifying it as an extra template argument to :class:`class_`. (This can also
  83. be combined with other template arguments such as a custom holder type; the
  84. order of template types does not matter). Following this, we are able to
  85. define a constructor as usual.
  86. Bindings should be made against the actual class, not the trampoline helper class.
  87. .. code-block:: cpp
  88. :emphasize-lines: 3
  89. py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal");
  90. .def(py::init<>())
  91. .def("go", &PyAnimal::go); /* <--- THIS IS WRONG, use &Animal::go */
  92. Note, however, that the above is sufficient for allowing python classes to
  93. extend ``Animal``, but not ``Dog``: see :ref:`virtual_and_inheritance` for the
  94. necessary steps required to providing proper overriding support for inherited
  95. classes.
  96. The Python session below shows how to override ``Animal::go`` and invoke it via
  97. a virtual method call.
  98. .. code-block:: pycon
  99. >>> from example import *
  100. >>> d = Dog()
  101. >>> call_go(d)
  102. u'woof! woof! woof! '
  103. >>> class Cat(Animal):
  104. ... def go(self, n_times):
  105. ... return "meow! " * n_times
  106. ...
  107. >>> c = Cat()
  108. >>> call_go(c)
  109. u'meow! meow! meow! '
  110. If you are defining a custom constructor in a derived Python class, you *must*
  111. ensure that you explicitly call the bound C++ constructor using ``__init__``,
  112. *regardless* of whether it is a default constructor or not. Otherwise, the
  113. memory for the C++ portion of the instance will be left uninitialized, which
  114. will generally leave the C++ instance in an invalid state and cause undefined
  115. behavior if the C++ instance is subsequently used.
  116. .. versionchanged:: 2.6
  117. The default pybind11 metaclass will throw a ``TypeError`` when it detects
  118. that ``__init__`` was not called by a derived class.
  119. Here is an example:
  120. .. code-block:: python
  121. class Dachshund(Dog):
  122. def __init__(self, name):
  123. Dog.__init__(self) # Without this, a TypeError is raised.
  124. self.name = name
  125. def bark(self):
  126. return "yap!"
  127. Note that a direct ``__init__`` constructor *should be called*, and ``super()``
  128. should not be used. For simple cases of linear inheritance, ``super()``
  129. may work, but once you begin mixing Python and C++ multiple inheritance,
  130. things will fall apart due to differences between Python's MRO and C++'s
  131. mechanisms.
  132. Please take a look at the :ref:`macro_notes` before using this feature.
  133. .. note::
  134. When the overridden type returns a reference or pointer to a type that
  135. pybind11 converts from Python (for example, numeric values, std::string,
  136. and other built-in value-converting types), there are some limitations to
  137. be aware of:
  138. - because in these cases there is no C++ variable to reference (the value
  139. is stored in the referenced Python variable), pybind11 provides one in
  140. the PYBIND11_OVERRIDE macros (when needed) with static storage duration.
  141. Note that this means that invoking the overridden method on *any*
  142. instance will change the referenced value stored in *all* instances of
  143. that type.
  144. - Attempts to modify a non-const reference will not have the desired
  145. effect: it will change only the static cache variable, but this change
  146. will not propagate to underlying Python instance, and the change will be
  147. replaced the next time the override is invoked.
  148. .. warning::
  149. The :c:macro:`PYBIND11_OVERRIDE` and accompanying macros used to be called
  150. ``PYBIND11_OVERLOAD`` up until pybind11 v2.5.0, and :func:`get_override`
  151. used to be called ``get_overload``. This naming was corrected and the older
  152. macro and function names may soon be deprecated, in order to reduce
  153. confusion with overloaded functions and methods and ``py::overload_cast``
  154. (see :ref:`classes`).
  155. .. seealso::
  156. The file :file:`tests/test_virtual_functions.cpp` contains a complete
  157. example that demonstrates how to override virtual functions using pybind11
  158. in more detail.
  159. .. _virtual_and_inheritance:
  160. Combining virtual functions and inheritance
  161. ===========================================
  162. When combining virtual methods with inheritance, you need to be sure to provide
  163. an override for each method for which you want to allow overrides from derived
  164. python classes. For example, suppose we extend the above ``Animal``/``Dog``
  165. example as follows:
  166. .. code-block:: cpp
  167. class Animal {
  168. public:
  169. virtual std::string go(int n_times) = 0;
  170. virtual std::string name() { return "unknown"; }
  171. };
  172. class Dog : public Animal {
  173. public:
  174. std::string go(int n_times) override {
  175. std::string result;
  176. for (int i=0; i<n_times; ++i)
  177. result += bark() + " ";
  178. return result;
  179. }
  180. virtual std::string bark() { return "woof!"; }
  181. };
  182. then the trampoline class for ``Animal`` must, as described in the previous
  183. section, override ``go()`` and ``name()``, but in order to allow python code to
  184. inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
  185. overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
  186. methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
  187. override the ``name()`` method):
  188. .. code-block:: cpp
  189. class PyAnimal : public Animal {
  190. public:
  191. using Animal::Animal; // Inherit constructors
  192. std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Animal, go, n_times); }
  193. std::string name() override { PYBIND11_OVERRIDE(std::string, Animal, name, ); }
  194. };
  195. class PyDog : public Dog {
  196. public:
  197. using Dog::Dog; // Inherit constructors
  198. std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, Dog, go, n_times); }
  199. std::string name() override { PYBIND11_OVERRIDE(std::string, Dog, name, ); }
  200. std::string bark() override { PYBIND11_OVERRIDE(std::string, Dog, bark, ); }
  201. };
  202. .. note::
  203. Note the trailing commas in the ``PYBIND11_OVERIDE`` calls to ``name()``
  204. and ``bark()``. These are needed to portably implement a trampoline for a
  205. function that does not take any arguments. For functions that take
  206. a nonzero number of arguments, the trailing comma must be omitted.
  207. A registered class derived from a pybind11-registered class with virtual
  208. methods requires a similar trampoline class, *even if* it doesn't explicitly
  209. declare or override any virtual methods itself:
  210. .. code-block:: cpp
  211. class Husky : public Dog {};
  212. class PyHusky : public Husky {
  213. public:
  214. using Husky::Husky; // Inherit constructors
  215. std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Husky, go, n_times); }
  216. std::string name() override { PYBIND11_OVERRIDE(std::string, Husky, name, ); }
  217. std::string bark() override { PYBIND11_OVERRIDE(std::string, Husky, bark, ); }
  218. };
  219. There is, however, a technique that can be used to avoid this duplication
  220. (which can be especially helpful for a base class with several virtual
  221. methods). The technique involves using template trampoline classes, as
  222. follows:
  223. .. code-block:: cpp
  224. template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
  225. public:
  226. using AnimalBase::AnimalBase; // Inherit constructors
  227. std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, AnimalBase, go, n_times); }
  228. std::string name() override { PYBIND11_OVERRIDE(std::string, AnimalBase, name, ); }
  229. };
  230. template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
  231. public:
  232. using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
  233. // Override PyAnimal's pure virtual go() with a non-pure one:
  234. std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, DogBase, go, n_times); }
  235. std::string bark() override { PYBIND11_OVERRIDE(std::string, DogBase, bark, ); }
  236. };
  237. This technique has the advantage of requiring just one trampoline method to be
  238. declared per virtual method and pure virtual method override. It does,
  239. however, require the compiler to generate at least as many methods (and
  240. possibly more, if both pure virtual and overridden pure virtual methods are
  241. exposed, as above).
  242. The classes are then registered with pybind11 using:
  243. .. code-block:: cpp
  244. py::class_<Animal, PyAnimal<>> animal(m, "Animal");
  245. py::class_<Dog, Animal, PyDog<>> dog(m, "Dog");
  246. py::class_<Husky, Dog, PyDog<Husky>> husky(m, "Husky");
  247. // ... add animal, dog, husky definitions
  248. Note that ``Husky`` did not require a dedicated trampoline template class at
  249. all, since it neither declares any new virtual methods nor provides any pure
  250. virtual method implementations.
  251. With either the repeated-virtuals or templated trampoline methods in place, you
  252. can now create a python class that inherits from ``Dog``:
  253. .. code-block:: python
  254. class ShihTzu(Dog):
  255. def bark(self):
  256. return "yip!"
  257. .. seealso::
  258. See the file :file:`tests/test_virtual_functions.cpp` for complete examples
  259. using both the duplication and templated trampoline approaches.
  260. .. _extended_aliases:
  261. Extended trampoline class functionality
  262. =======================================
  263. .. _extended_class_functionality_forced_trampoline:
  264. Forced trampoline class initialisation
  265. --------------------------------------
  266. The trampoline classes described in the previous sections are, by default, only
  267. initialized when needed. More specifically, they are initialized when a python
  268. class actually inherits from a registered type (instead of merely creating an
  269. instance of the registered type), or when a registered constructor is only
  270. valid for the trampoline class but not the registered class. This is primarily
  271. for performance reasons: when the trampoline class is not needed for anything
  272. except virtual method dispatching, not initializing the trampoline class
  273. improves performance by avoiding needing to do a run-time check to see if the
  274. inheriting python instance has an overridden method.
  275. Sometimes, however, it is useful to always initialize a trampoline class as an
  276. intermediate class that does more than just handle virtual method dispatching.
  277. For example, such a class might perform extra class initialization, extra
  278. destruction operations, and might define new members and methods to enable a
  279. more python-like interface to a class.
  280. In order to tell pybind11 that it should *always* initialize the trampoline
  281. class when creating new instances of a type, the class constructors should be
  282. declared using ``py::init_alias<Args, ...>()`` instead of the usual
  283. ``py::init<Args, ...>()``. This forces construction via the trampoline class,
  284. ensuring member initialization and (eventual) destruction.
  285. .. seealso::
  286. See the file :file:`tests/test_virtual_functions.cpp` for complete examples
  287. showing both normal and forced trampoline instantiation.
  288. Different method signatures
  289. ---------------------------
  290. The macro's introduced in :ref:`overriding_virtuals` cover most of the standard
  291. use cases when exposing C++ classes to Python. Sometimes it is hard or unwieldy
  292. to create a direct one-on-one mapping between the arguments and method return
  293. type.
  294. An example would be when the C++ signature contains output arguments using
  295. references (See also :ref:`faq_reference_arguments`). Another way of solving
  296. this is to use the method body of the trampoline class to do conversions to the
  297. input and return of the Python method.
  298. The main building block to do so is the :func:`get_override`, this function
  299. allows retrieving a method implemented in Python from within the trampoline's
  300. methods. Consider for example a C++ method which has the signature
  301. ``bool myMethod(int32_t& value)``, where the return indicates whether
  302. something should be done with the ``value``. This can be made convenient on the
  303. Python side by allowing the Python function to return ``None`` or an ``int``:
  304. .. code-block:: cpp
  305. bool MyClass::myMethod(int32_t& value)
  306. {
  307. pybind11::gil_scoped_acquire gil; // Acquire the GIL while in this scope.
  308. // Try to look up the overridden method on the Python side.
  309. pybind11::function override = pybind11::get_override(this, "myMethod");
  310. if (override) { // method is found
  311. auto obj = override(value); // Call the Python function.
  312. if (py::isinstance<py::int_>(obj)) { // check if it returned a Python integer type
  313. value = obj.cast<int32_t>(); // Cast it and assign it to the value.
  314. return true; // Return true; value should be used.
  315. } else {
  316. return false; // Python returned none, return false.
  317. }
  318. }
  319. return false; // Alternatively return MyClass::myMethod(value);
  320. }
  321. .. _custom_constructors:
  322. Custom constructors
  323. ===================
  324. The syntax for binding constructors was previously introduced, but it only
  325. works when a constructor of the appropriate arguments actually exists on the
  326. C++ side. To extend this to more general cases, pybind11 makes it possible
  327. to bind factory functions as constructors. For example, suppose you have a
  328. class like this:
  329. .. code-block:: cpp
  330. class Example {
  331. private:
  332. Example(int); // private constructor
  333. public:
  334. // Factory function:
  335. static Example create(int a) { return Example(a); }
  336. };
  337. py::class_<Example>(m, "Example")
  338. .def(py::init(&Example::create));
  339. While it is possible to create a straightforward binding of the static
  340. ``create`` method, it may sometimes be preferable to expose it as a constructor
  341. on the Python side. This can be accomplished by calling ``.def(py::init(...))``
  342. with the function reference returning the new instance passed as an argument.
  343. It is also possible to use this approach to bind a function returning a new
  344. instance by raw pointer or by the holder (e.g. ``std::unique_ptr``).
  345. The following example shows the different approaches:
  346. .. code-block:: cpp
  347. class Example {
  348. private:
  349. Example(int); // private constructor
  350. public:
  351. // Factory function - returned by value:
  352. static Example create(int a) { return Example(a); }
  353. // These constructors are publicly callable:
  354. Example(double);
  355. Example(int, int);
  356. Example(std::string);
  357. };
  358. py::class_<Example>(m, "Example")
  359. // Bind the factory function as a constructor:
  360. .def(py::init(&Example::create))
  361. // Bind a lambda function returning a pointer wrapped in a holder:
  362. .def(py::init([](std::string arg) {
  363. return std::unique_ptr<Example>(new Example(arg));
  364. }))
  365. // Return a raw pointer:
  366. .def(py::init([](int a, int b) { return new Example(a, b); }))
  367. // You can mix the above with regular C++ constructor bindings as well:
  368. .def(py::init<double>())
  369. ;
  370. When the constructor is invoked from Python, pybind11 will call the factory
  371. function and store the resulting C++ instance in the Python instance.
  372. When combining factory functions constructors with :ref:`virtual function
  373. trampolines <overriding_virtuals>` there are two approaches. The first is to
  374. add a constructor to the alias class that takes a base value by
  375. rvalue-reference. If such a constructor is available, it will be used to
  376. construct an alias instance from the value returned by the factory function.
  377. The second option is to provide two factory functions to ``py::init()``: the
  378. first will be invoked when no alias class is required (i.e. when the class is
  379. being used but not inherited from in Python), and the second will be invoked
  380. when an alias is required.
  381. You can also specify a single factory function that always returns an alias
  382. instance: this will result in behaviour similar to ``py::init_alias<...>()``,
  383. as described in the :ref:`extended trampoline class documentation
  384. <extended_aliases>`.
  385. The following example shows the different factory approaches for a class with
  386. an alias:
  387. .. code-block:: cpp
  388. #include <pybind11/factory.h>
  389. class Example {
  390. public:
  391. // ...
  392. virtual ~Example() = default;
  393. };
  394. class PyExample : public Example {
  395. public:
  396. using Example::Example;
  397. PyExample(Example &&base) : Example(std::move(base)) {}
  398. };
  399. py::class_<Example, PyExample>(m, "Example")
  400. // Returns an Example pointer. If a PyExample is needed, the Example
  401. // instance will be moved via the extra constructor in PyExample, above.
  402. .def(py::init([]() { return new Example(); }))
  403. // Two callbacks:
  404. .def(py::init([]() { return new Example(); } /* no alias needed */,
  405. []() { return new PyExample(); } /* alias needed */))
  406. // *Always* returns an alias instance (like py::init_alias<>())
  407. .def(py::init([]() { return new PyExample(); }))
  408. ;
  409. Brace initialization
  410. --------------------
  411. ``pybind11::init<>`` internally uses C++11 brace initialization to call the
  412. constructor of the target class. This means that it can be used to bind
  413. *implicit* constructors as well:
  414. .. code-block:: cpp
  415. struct Aggregate {
  416. int a;
  417. std::string b;
  418. };
  419. py::class_<Aggregate>(m, "Aggregate")
  420. .def(py::init<int, const std::string &>());
  421. .. note::
  422. Note that brace initialization preferentially invokes constructor overloads
  423. taking a ``std::initializer_list``. In the rare event that this causes an
  424. issue, you can work around it by using ``py::init(...)`` with a lambda
  425. function that constructs the new object as desired.
  426. .. _classes_with_non_public_destructors:
  427. Non-public destructors
  428. ======================
  429. If a class has a private or protected destructor (as might e.g. be the case in
  430. a singleton pattern), a compile error will occur when creating bindings via
  431. pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
  432. is responsible for managing the lifetime of instances will reference the
  433. destructor even if no deallocations ever take place. In order to expose classes
  434. with private or protected destructors, it is possible to override the holder
  435. type via a holder type argument to ``class_``. Pybind11 provides a helper class
  436. ``py::nodelete`` that disables any destructor invocations. In this case, it is
  437. crucial that instances are deallocated on the C++ side to avoid memory leaks.
  438. .. code-block:: cpp
  439. /* ... definition ... */
  440. class MyClass {
  441. private:
  442. ~MyClass() { }
  443. };
  444. /* ... binding code ... */
  445. py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
  446. .def(py::init<>())
  447. .. _destructors_that_call_python:
  448. Destructors that call Python
  449. ============================
  450. If a Python function is invoked from a C++ destructor, an exception may be thrown
  451. of type :class:`error_already_set`. If this error is thrown out of a class destructor,
  452. ``std::terminate()`` will be called, terminating the process. Class destructors
  453. must catch all exceptions of type :class:`error_already_set` to discard the Python
  454. exception using :func:`error_already_set::discard_as_unraisable`.
  455. Every Python function should be treated as *possibly throwing*. When a Python generator
  456. stops yielding items, Python will throw a ``StopIteration`` exception, which can pass
  457. though C++ destructors if the generator's stack frame holds the last reference to C++
  458. objects.
  459. For more information, see :ref:`the documentation on exceptions <unraisable_exceptions>`.
  460. .. code-block:: cpp
  461. class MyClass {
  462. public:
  463. ~MyClass() {
  464. try {
  465. py::print("Even printing is dangerous in a destructor");
  466. py::exec("raise ValueError('This is an unraisable exception')");
  467. } catch (py::error_already_set &e) {
  468. // error_context should be information about where/why the occurred,
  469. // e.g. use __func__ to get the name of the current function
  470. e.discard_as_unraisable(__func__);
  471. }
  472. }
  473. };
  474. .. note::
  475. pybind11 does not support C++ destructors marked ``noexcept(false)``.
  476. .. versionadded:: 2.6
  477. .. _implicit_conversions:
  478. Implicit conversions
  479. ====================
  480. Suppose that instances of two types ``A`` and ``B`` are used in a project, and
  481. that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
  482. could be a fixed and an arbitrary precision number type).
  483. .. code-block:: cpp
  484. py::class_<A>(m, "A")
  485. /// ... members ...
  486. py::class_<B>(m, "B")
  487. .def(py::init<A>())
  488. /// ... members ...
  489. m.def("func",
  490. [](const B &) { /* .... */ }
  491. );
  492. To invoke the function ``func`` using a variable ``a`` containing an ``A``
  493. instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
  494. will automatically apply an implicit type conversion, which makes it possible
  495. to directly write ``func(a)``.
  496. In this situation (i.e. where ``B`` has a constructor that converts from
  497. ``A``), the following statement enables similar implicit conversions on the
  498. Python side:
  499. .. code-block:: cpp
  500. py::implicitly_convertible<A, B>();
  501. .. note::
  502. Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
  503. data type that is exposed to Python via pybind11.
  504. To prevent runaway recursion, implicit conversions are non-reentrant: an
  505. implicit conversion invoked as part of another implicit conversion of the
  506. same type (i.e. from ``A`` to ``B``) will fail.
  507. .. _static_properties:
  508. Static properties
  509. =================
  510. The section on :ref:`properties` discussed the creation of instance properties
  511. that are implemented in terms of C++ getters and setters.
  512. Static properties can also be created in a similar way to expose getters and
  513. setters of static class attributes. Note that the implicit ``self`` argument
  514. also exists in this case and is used to pass the Python ``type`` subclass
  515. instance. This parameter will often not be needed by the C++ side, and the
  516. following example illustrates how to instantiate a lambda getter function
  517. that ignores it:
  518. .. code-block:: cpp
  519. py::class_<Foo>(m, "Foo")
  520. .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
  521. Operator overloading
  522. ====================
  523. Suppose that we're given the following ``Vector2`` class with a vector addition
  524. and scalar multiplication operation, all implemented using overloaded operators
  525. in C++.
  526. .. code-block:: cpp
  527. class Vector2 {
  528. public:
  529. Vector2(float x, float y) : x(x), y(y) { }
  530. Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
  531. Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
  532. Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
  533. Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
  534. friend Vector2 operator*(float f, const Vector2 &v) {
  535. return Vector2(f * v.x, f * v.y);
  536. }
  537. std::string toString() const {
  538. return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
  539. }
  540. private:
  541. float x, y;
  542. };
  543. The following snippet shows how the above operators can be conveniently exposed
  544. to Python.
  545. .. code-block:: cpp
  546. #include <pybind11/operators.h>
  547. PYBIND11_MODULE(example, m) {
  548. py::class_<Vector2>(m, "Vector2")
  549. .def(py::init<float, float>())
  550. .def(py::self + py::self)
  551. .def(py::self += py::self)
  552. .def(py::self *= float())
  553. .def(float() * py::self)
  554. .def(py::self * float())
  555. .def(-py::self)
  556. .def("__repr__", &Vector2::toString);
  557. }
  558. Note that a line like
  559. .. code-block:: cpp
  560. .def(py::self * float())
  561. is really just short hand notation for
  562. .. code-block:: cpp
  563. .def("__mul__", [](const Vector2 &a, float b) {
  564. return a * b;
  565. }, py::is_operator())
  566. This can be useful for exposing additional operators that don't exist on the
  567. C++ side, or to perform other types of customization. The ``py::is_operator``
  568. flag marker is needed to inform pybind11 that this is an operator, which
  569. returns ``NotImplemented`` when invoked with incompatible arguments rather than
  570. throwing a type error.
  571. .. note::
  572. To use the more convenient ``py::self`` notation, the additional
  573. header file :file:`pybind11/operators.h` must be included.
  574. .. seealso::
  575. The file :file:`tests/test_operator_overloading.cpp` contains a
  576. complete example that demonstrates how to work with overloaded operators in
  577. more detail.
  578. .. _pickling:
  579. Pickling support
  580. ================
  581. Python's ``pickle`` module provides a powerful facility to serialize and
  582. de-serialize a Python object graph into a binary data stream. To pickle and
  583. unpickle C++ classes using pybind11, a ``py::pickle()`` definition must be
  584. provided. Suppose the class in question has the following signature:
  585. .. code-block:: cpp
  586. class Pickleable {
  587. public:
  588. Pickleable(const std::string &value) : m_value(value) { }
  589. const std::string &value() const { return m_value; }
  590. void setExtra(int extra) { m_extra = extra; }
  591. int extra() const { return m_extra; }
  592. private:
  593. std::string m_value;
  594. int m_extra = 0;
  595. };
  596. Pickling support in Python is enabled by defining the ``__setstate__`` and
  597. ``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()``
  598. to bind these two functions:
  599. .. code-block:: cpp
  600. py::class_<Pickleable>(m, "Pickleable")
  601. .def(py::init<std::string>())
  602. .def("value", &Pickleable::value)
  603. .def("extra", &Pickleable::extra)
  604. .def("setExtra", &Pickleable::setExtra)
  605. .def(py::pickle(
  606. [](const Pickleable &p) { // __getstate__
  607. /* Return a tuple that fully encodes the state of the object */
  608. return py::make_tuple(p.value(), p.extra());
  609. },
  610. [](py::tuple t) { // __setstate__
  611. if (t.size() != 2)
  612. throw std::runtime_error("Invalid state!");
  613. /* Create a new C++ instance */
  614. Pickleable p(t[0].cast<std::string>());
  615. /* Assign any additional state */
  616. p.setExtra(t[1].cast<int>());
  617. return p;
  618. }
  619. ));
  620. The ``__setstate__`` part of the ``py::picke()`` definition follows the same
  621. rules as the single-argument version of ``py::init()``. The return type can be
  622. a value, pointer or holder type. See :ref:`custom_constructors` for details.
  623. An instance can now be pickled as follows:
  624. .. code-block:: python
  625. try:
  626. import cPickle as pickle # Use cPickle on Python 2.7
  627. except ImportError:
  628. import pickle
  629. p = Pickleable("test_value")
  630. p.setExtra(15)
  631. data = pickle.dumps(p, 2)
  632. .. note::
  633. Note that only the cPickle module is supported on Python 2.7.
  634. The second argument to ``dumps`` is also crucial: it selects the pickle
  635. protocol version 2, since the older version 1 is not supported. Newer
  636. versions are also fine—for instance, specify ``-1`` to always use the
  637. latest available version. Beware: failure to follow these instructions
  638. will cause important pybind11 memory allocation routines to be skipped
  639. during unpickling, which will likely lead to memory corruption and/or
  640. segmentation faults.
  641. .. seealso::
  642. The file :file:`tests/test_pickling.cpp` contains a complete example
  643. that demonstrates how to pickle and unpickle types using pybind11 in more
  644. detail.
  645. .. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
  646. Deepcopy support
  647. ================
  648. Python normally uses references in assignments. Sometimes a real copy is needed
  649. to prevent changing all copies. The ``copy`` module [#f5]_ provides these
  650. capabilities.
  651. On Python 3, a class with pickle support is automatically also (deep)copy
  652. compatible. However, performance can be improved by adding custom
  653. ``__copy__`` and ``__deepcopy__`` methods. With Python 2.7, these custom methods
  654. are mandatory for (deep)copy compatibility, because pybind11 only supports
  655. cPickle.
  656. For simple classes (deep)copy can be enabled by using the copy constructor,
  657. which should look as follows:
  658. .. code-block:: cpp
  659. py::class_<Copyable>(m, "Copyable")
  660. .def("__copy__", [](const Copyable &self) {
  661. return Copyable(self);
  662. })
  663. .def("__deepcopy__", [](const Copyable &self, py::dict) {
  664. return Copyable(self);
  665. }, "memo"_a);
  666. .. note::
  667. Dynamic attributes will not be copied in this example.
  668. .. [#f5] https://docs.python.org/3/library/copy.html
  669. Multiple Inheritance
  670. ====================
  671. pybind11 can create bindings for types that derive from multiple base types
  672. (aka. *multiple inheritance*). To do so, specify all bases in the template
  673. arguments of the ``class_`` declaration:
  674. .. code-block:: cpp
  675. py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
  676. ...
  677. The base types can be specified in arbitrary order, and they can even be
  678. interspersed with alias types and holder types (discussed earlier in this
  679. document)---pybind11 will automatically find out which is which. The only
  680. requirement is that the first template argument is the type to be declared.
  681. It is also permitted to inherit multiply from exported C++ classes in Python,
  682. as well as inheriting from multiple Python and/or pybind11-exported classes.
  683. There is one caveat regarding the implementation of this feature:
  684. When only one base type is specified for a C++ type that actually has multiple
  685. bases, pybind11 will assume that it does not participate in multiple
  686. inheritance, which can lead to undefined behavior. In such cases, add the tag
  687. ``multiple_inheritance`` to the class constructor:
  688. .. code-block:: cpp
  689. py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
  690. The tag is redundant and does not need to be specified when multiple base types
  691. are listed.
  692. .. _module_local:
  693. Module-local class bindings
  694. ===========================
  695. When creating a binding for a class, pybind11 by default makes that binding
  696. "global" across modules. What this means is that a type defined in one module
  697. can be returned from any module resulting in the same Python type. For
  698. example, this allows the following:
  699. .. code-block:: cpp
  700. // In the module1.cpp binding code for module1:
  701. py::class_<Pet>(m, "Pet")
  702. .def(py::init<std::string>())
  703. .def_readonly("name", &Pet::name);
  704. .. code-block:: cpp
  705. // In the module2.cpp binding code for module2:
  706. m.def("create_pet", [](std::string name) { return new Pet(name); });
  707. .. code-block:: pycon
  708. >>> from module1 import Pet
  709. >>> from module2 import create_pet
  710. >>> pet1 = Pet("Kitty")
  711. >>> pet2 = create_pet("Doggy")
  712. >>> pet2.name()
  713. 'Doggy'
  714. When writing binding code for a library, this is usually desirable: this
  715. allows, for example, splitting up a complex library into multiple Python
  716. modules.
  717. In some cases, however, this can cause conflicts. For example, suppose two
  718. unrelated modules make use of an external C++ library and each provide custom
  719. bindings for one of that library's classes. This will result in an error when
  720. a Python program attempts to import both modules (directly or indirectly)
  721. because of conflicting definitions on the external type:
  722. .. code-block:: cpp
  723. // dogs.cpp
  724. // Binding for external library class:
  725. py::class<pets::Pet>(m, "Pet")
  726. .def("name", &pets::Pet::name);
  727. // Binding for local extension class:
  728. py::class<Dog, pets::Pet>(m, "Dog")
  729. .def(py::init<std::string>());
  730. .. code-block:: cpp
  731. // cats.cpp, in a completely separate project from the above dogs.cpp.
  732. // Binding for external library class:
  733. py::class<pets::Pet>(m, "Pet")
  734. .def("get_name", &pets::Pet::name);
  735. // Binding for local extending class:
  736. py::class<Cat, pets::Pet>(m, "Cat")
  737. .def(py::init<std::string>());
  738. .. code-block:: pycon
  739. >>> import cats
  740. >>> import dogs
  741. Traceback (most recent call last):
  742. File "<stdin>", line 1, in <module>
  743. ImportError: generic_type: type "Pet" is already registered!
  744. To get around this, you can tell pybind11 to keep the external class binding
  745. localized to the module by passing the ``py::module_local()`` attribute into
  746. the ``py::class_`` constructor:
  747. .. code-block:: cpp
  748. // Pet binding in dogs.cpp:
  749. py::class<pets::Pet>(m, "Pet", py::module_local())
  750. .def("name", &pets::Pet::name);
  751. .. code-block:: cpp
  752. // Pet binding in cats.cpp:
  753. py::class<pets::Pet>(m, "Pet", py::module_local())
  754. .def("get_name", &pets::Pet::name);
  755. This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes,
  756. avoiding the conflict and allowing both modules to be loaded. C++ code in the
  757. ``dogs`` module that casts or returns a ``Pet`` instance will result in a
  758. ``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result
  759. in a ``cats.Pet`` Python instance.
  760. This does come with two caveats, however: First, external modules cannot return
  761. or cast a ``Pet`` instance to Python (unless they also provide their own local
  762. bindings). Second, from the Python point of view they are two distinct classes.
  763. Note that the locality only applies in the C++ -> Python direction. When
  764. passing such a ``py::module_local`` type into a C++ function, the module-local
  765. classes are still considered. This means that if the following function is
  766. added to any module (including but not limited to the ``cats`` and ``dogs``
  767. modules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet``
  768. argument:
  769. .. code-block:: cpp
  770. m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); });
  771. For example, suppose the above function is added to each of ``cats.cpp``,
  772. ``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that
  773. does *not* bind ``Pets`` at all).
  774. .. code-block:: pycon
  775. >>> import cats, dogs, frogs # No error because of the added py::module_local()
  776. >>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover")
  777. >>> (cats.pet_name(mycat), dogs.pet_name(mydog))
  778. ('Fluffy', 'Rover')
  779. >>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat))
  780. ('Rover', 'Fluffy', 'Fluffy')
  781. It is possible to use ``py::module_local()`` registrations in one module even
  782. if another module registers the same type globally: within the module with the
  783. module-local definition, all C++ instances will be cast to the associated bound
  784. Python type. In other modules any such values are converted to the global
  785. Python type created elsewhere.
  786. .. note::
  787. STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`
  788. header) apply ``py::module_local`` by default when the bound type might
  789. conflict with other modules; see :ref:`stl_bind` for details.
  790. .. note::
  791. The localization of the bound types is actually tied to the shared object
  792. or binary generated by the compiler/linker. For typical modules created
  793. with ``PYBIND11_MODULE()``, this distinction is not significant. It is
  794. possible, however, when :ref:`embedding` to embed multiple modules in the
  795. same binary (see :ref:`embedding_modules`). In such a case, the
  796. localization will apply across all embedded modules within the same binary.
  797. .. seealso::
  798. The file :file:`tests/test_local_bindings.cpp` contains additional examples
  799. that demonstrate how ``py::module_local()`` works.
  800. Binding protected member functions
  801. ==================================
  802. It's normally not possible to expose ``protected`` member functions to Python:
  803. .. code-block:: cpp
  804. class A {
  805. protected:
  806. int foo() const { return 42; }
  807. };
  808. py::class_<A>(m, "A")
  809. .def("foo", &A::foo); // error: 'foo' is a protected member of 'A'
  810. On one hand, this is good because non-``public`` members aren't meant to be
  811. accessed from the outside. But we may want to make use of ``protected``
  812. functions in derived Python classes.
  813. The following pattern makes this possible:
  814. .. code-block:: cpp
  815. class A {
  816. protected:
  817. int foo() const { return 42; }
  818. };
  819. class Publicist : public A { // helper type for exposing protected functions
  820. public:
  821. using A::foo; // inherited with different access modifier
  822. };
  823. py::class_<A>(m, "A") // bind the primary class
  824. .def("foo", &Publicist::foo); // expose protected methods via the publicist
  825. This works because ``&Publicist::foo`` is exactly the same function as
  826. ``&A::foo`` (same signature and address), just with a different access
  827. modifier. The only purpose of the ``Publicist`` helper class is to make
  828. the function name ``public``.
  829. If the intent is to expose ``protected`` ``virtual`` functions which can be
  830. overridden in Python, the publicist pattern can be combined with the previously
  831. described trampoline:
  832. .. code-block:: cpp
  833. class A {
  834. public:
  835. virtual ~A() = default;
  836. protected:
  837. virtual int foo() const { return 42; }
  838. };
  839. class Trampoline : public A {
  840. public:
  841. int foo() const override { PYBIND11_OVERRIDE(int, A, foo, ); }
  842. };
  843. class Publicist : public A {
  844. public:
  845. using A::foo;
  846. };
  847. py::class_<A, Trampoline>(m, "A") // <-- `Trampoline` here
  848. .def("foo", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`!
  849. .. note::
  850. MSVC 2015 has a compiler bug (fixed in version 2017) which
  851. requires a more explicit function binding in the form of
  852. ``.def("foo", static_cast<int (A::*)() const>(&Publicist::foo));``
  853. where ``int (A::*)() const`` is the type of ``A::foo``.
  854. Binding final classes
  855. =====================
  856. Some classes may not be appropriate to inherit from. In C++11, classes can
  857. use the ``final`` specifier to ensure that a class cannot be inherited from.
  858. The ``py::is_final`` attribute can be used to ensure that Python classes
  859. cannot inherit from a specified type. The underlying C++ type does not need
  860. to be declared final.
  861. .. code-block:: cpp
  862. class IsFinal final {};
  863. py::class_<IsFinal>(m, "IsFinal", py::is_final());
  864. When you try to inherit from such a class in Python, you will now get this
  865. error:
  866. .. code-block:: pycon
  867. >>> class PyFinalChild(IsFinal):
  868. ... pass
  869. TypeError: type 'IsFinal' is not an acceptable base type
  870. .. note:: This attribute is currently ignored on PyPy
  871. .. versionadded:: 2.6
  872. Custom automatic downcasters
  873. ============================
  874. As explained in :ref:`inheritance`, pybind11 comes with built-in
  875. understanding of the dynamic type of polymorphic objects in C++; that
  876. is, returning a Pet to Python produces a Python object that knows it's
  877. wrapping a Dog, if Pet has virtual methods and pybind11 knows about
  878. Dog and this Pet is in fact a Dog. Sometimes, you might want to
  879. provide this automatic downcasting behavior when creating bindings for
  880. a class hierarchy that does not use standard C++ polymorphism, such as
  881. LLVM [#f4]_. As long as there's some way to determine at runtime
  882. whether a downcast is safe, you can proceed by specializing the
  883. ``pybind11::polymorphic_type_hook`` template:
  884. .. code-block:: cpp
  885. enum class PetKind { Cat, Dog, Zebra };
  886. struct Pet { // Not polymorphic: has no virtual methods
  887. const PetKind kind;
  888. int age = 0;
  889. protected:
  890. Pet(PetKind _kind) : kind(_kind) {}
  891. };
  892. struct Dog : Pet {
  893. Dog() : Pet(PetKind::Dog) {}
  894. std::string sound = "woof!";
  895. std::string bark() const { return sound; }
  896. };
  897. namespace pybind11 {
  898. template<> struct polymorphic_type_hook<Pet> {
  899. static const void *get(const Pet *src, const std::type_info*& type) {
  900. // note that src may be nullptr
  901. if (src && src->kind == PetKind::Dog) {
  902. type = &typeid(Dog);
  903. return static_cast<const Dog*>(src);
  904. }
  905. return src;
  906. }
  907. };
  908. } // namespace pybind11
  909. When pybind11 wants to convert a C++ pointer of type ``Base*`` to a
  910. Python object, it calls ``polymorphic_type_hook<Base>::get()`` to
  911. determine if a downcast is possible. The ``get()`` function should use
  912. whatever runtime information is available to determine if its ``src``
  913. parameter is in fact an instance of some class ``Derived`` that
  914. inherits from ``Base``. If it finds such a ``Derived``, it sets ``type
  915. = &typeid(Derived)`` and returns a pointer to the ``Derived`` object
  916. that contains ``src``. Otherwise, it just returns ``src``, leaving
  917. ``type`` at its default value of nullptr. If you set ``type`` to a
  918. type that pybind11 doesn't know about, no downcasting will occur, and
  919. the original ``src`` pointer will be used with its static type
  920. ``Base*``.
  921. It is critical that the returned pointer and ``type`` argument of
  922. ``get()`` agree with each other: if ``type`` is set to something
  923. non-null, the returned pointer must point to the start of an object
  924. whose type is ``type``. If the hierarchy being exposed uses only
  925. single inheritance, a simple ``return src;`` will achieve this just
  926. fine, but in the general case, you must cast ``src`` to the
  927. appropriate derived-class pointer (e.g. using
  928. ``static_cast<Derived>(src)``) before allowing it to be returned as a
  929. ``void*``.
  930. .. [#f4] https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html
  931. .. note::
  932. pybind11's standard support for downcasting objects whose types
  933. have virtual methods is implemented using
  934. ``polymorphic_type_hook`` too, using the standard C++ ability to
  935. determine the most-derived type of a polymorphic object using
  936. ``typeid()`` and to cast a base pointer to that most-derived type
  937. (even if you don't know what it is) using ``dynamic_cast<void*>``.
  938. .. seealso::
  939. The file :file:`tests/test_tagbased_polymorphic.cpp` contains a
  940. more complete example, including a demonstration of how to provide
  941. automatic downcasting for an entire class hierarchy without
  942. writing one get() function for each class.
  943. Accessing the type object
  944. =========================
  945. You can get the type object from a C++ class that has already been registered using:
  946. .. code-block:: python
  947. py::type T_py = py::type::of<T>();
  948. You can directly use ``py::type::of(ob)`` to get the type object from any python
  949. object, just like ``type(ob)`` in Python.
  950. .. note::
  951. Other types, like ``py::type::of<int>()``, do not work, see :ref:`type-conversions`.
  952. .. versionadded:: 2.6