You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

634 lines
22 KiB

  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_PLUGIN(example) {
  36. py::module m("example", "pybind11 example plugin");
  37. py::class_<Animal> animal(m, "Animal");
  38. animal
  39. .def("go", &Animal::go);
  40. py::class_<Dog>(m, "Dog", animal)
  41. .def(py::init<>());
  42. m.def("call_go", &call_go);
  43. return m.ptr();
  44. }
  45. However, these bindings are impossible to extend: ``Animal`` is not
  46. constructible, and we clearly require some kind of "trampoline" that
  47. redirects virtual calls back to Python.
  48. Defining a new type of ``Animal`` from within Python is possible but requires a
  49. helper class that is defined as follows:
  50. .. code-block:: cpp
  51. class PyAnimal : public Animal {
  52. public:
  53. /* Inherit the constructors */
  54. using Animal::Animal;
  55. /* Trampoline (need one for each virtual function) */
  56. std::string go(int n_times) override {
  57. PYBIND11_OVERLOAD_PURE(
  58. std::string, /* Return type */
  59. Animal, /* Parent class */
  60. go, /* Name of function */
  61. n_times /* Argument(s) */
  62. );
  63. }
  64. };
  65. The macro :func:`PYBIND11_OVERLOAD_PURE` should be used for pure virtual
  66. functions, and :func:`PYBIND11_OVERLOAD` should be used for functions which have
  67. a default implementation. There are also two alternate macros
  68. :func:`PYBIND11_OVERLOAD_PURE_NAME` and :func:`PYBIND11_OVERLOAD_NAME` which
  69. take a string-valued name argument between the *Parent class* and *Name of the
  70. function* slots. This is useful when the C++ and Python versions of the
  71. function have different names, e.g. ``operator()`` vs ``__call__``.
  72. The binding code also needs a few minor adaptations (highlighted):
  73. .. code-block:: cpp
  74. :emphasize-lines: 4,6,7
  75. PYBIND11_PLUGIN(example) {
  76. py::module m("example", "pybind11 example plugin");
  77. py::class_<Animal, PyAnimal /* <--- trampoline*/> animal(m, "Animal");
  78. animal
  79. .def(py::init<>())
  80. .def("go", &Animal::go);
  81. py::class_<Dog>(m, "Dog", animal)
  82. .def(py::init<>());
  83. m.def("call_go", &call_go);
  84. return m.ptr();
  85. }
  86. Importantly, pybind11 is made aware of the trampoline helper class by
  87. specifying it as an extra template argument to :class:`class_`. (This can also
  88. be combined with other template arguments such as a custom holder type; the
  89. order of template types does not matter). Following this, we are able to
  90. define a constructor as usual.
  91. Note, however, that the above is sufficient for allowing python classes to
  92. extend ``Animal``, but not ``Dog``: see ref:`virtual_and_inheritance` for the
  93. necessary steps required to providing proper overload support for inherited
  94. classes.
  95. The Python session below shows how to override ``Animal::go`` and invoke it via
  96. a virtual method call.
  97. .. code-block:: pycon
  98. >>> from example import *
  99. >>> d = Dog()
  100. >>> call_go(d)
  101. u'woof! woof! woof! '
  102. >>> class Cat(Animal):
  103. ... def go(self, n_times):
  104. ... return "meow! " * n_times
  105. ...
  106. >>> c = Cat()
  107. >>> call_go(c)
  108. u'meow! meow! meow! '
  109. Please take a look at the :ref:`macro_notes` before using this feature.
  110. .. note::
  111. When the overridden type returns a reference or pointer to a type that
  112. pybind11 converts from Python (for example, numeric values, std::string,
  113. and other built-in value-converting types), there are some limitations to
  114. be aware of:
  115. - because in these cases there is no C++ variable to reference (the value
  116. is stored in the referenced Python variable), pybind11 provides one in
  117. the PYBIND11_OVERLOAD macros (when needed) with static storage duration.
  118. Note that this means that invoking the overloaded method on *any*
  119. instance will change the referenced value stored in *all* instances of
  120. that type.
  121. - Attempts to modify a non-const reference will not have the desired
  122. effect: it will change only the static cache variable, but this change
  123. will not propagate to underlying Python instance, and the change will be
  124. replaced the next time the overload is invoked.
  125. .. seealso::
  126. The file :file:`tests/test_virtual_functions.cpp` contains a complete
  127. example that demonstrates how to override virtual functions using pybind11
  128. in more detail.
  129. .. _virtual_and_inheritance:
  130. Combining virtual functions and inheritance
  131. ===========================================
  132. When combining virtual methods with inheritance, you need to be sure to provide
  133. an override for each method for which you want to allow overrides from derived
  134. python classes. For example, suppose we extend the above ``Animal``/``Dog``
  135. example as follows:
  136. .. code-block:: cpp
  137. class Animal {
  138. public:
  139. virtual std::string go(int n_times) = 0;
  140. virtual std::string name() { return "unknown"; }
  141. };
  142. class Dog : public class Animal {
  143. public:
  144. std::string go(int n_times) override {
  145. std::string result;
  146. for (int i=0; i<n_times; ++i)
  147. result += bark() + " ";
  148. return result;
  149. }
  150. virtual std::string bark() { return "woof!"; }
  151. };
  152. then the trampoline class for ``Animal`` must, as described in the previous
  153. section, override ``go()`` and ``name()``, but in order to allow python code to
  154. inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
  155. overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
  156. methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
  157. override the ``name()`` method):
  158. .. code-block:: cpp
  159. class PyAnimal : public Animal {
  160. public:
  161. using Animal::Animal; // Inherit constructors
  162. std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Animal, go, n_times); }
  163. std::string name() override { PYBIND11_OVERLOAD(std::string, Animal, name, ); }
  164. };
  165. class PyDog : public Dog {
  166. public:
  167. using Dog::Dog; // Inherit constructors
  168. std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Dog, go, n_times); }
  169. std::string name() override { PYBIND11_OVERLOAD(std::string, Dog, name, ); }
  170. std::string bark() override { PYBIND11_OVERLOAD(std::string, Dog, bark, ); }
  171. };
  172. A registered class derived from a pybind11-registered class with virtual
  173. methods requires a similar trampoline class, *even if* it doesn't explicitly
  174. declare or override any virtual methods itself:
  175. .. code-block:: cpp
  176. class Husky : public Dog {};
  177. class PyHusky : public Husky {
  178. using Dog::Dog; // Inherit constructors
  179. std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, Husky, go, n_times); }
  180. std::string name() override { PYBIND11_OVERLOAD(std::string, Husky, name, ); }
  181. std::string bark() override { PYBIND11_OVERLOAD(std::string, Husky, bark, ); }
  182. };
  183. There is, however, a technique that can be used to avoid this duplication
  184. (which can be especially helpful for a base class with several virtual
  185. methods). The technique involves using template trampoline classes, as
  186. follows:
  187. .. code-block:: cpp
  188. template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
  189. using AnimalBase::AnimalBase; // Inherit constructors
  190. std::string go(int n_times) override { PYBIND11_OVERLOAD_PURE(std::string, AnimalBase, go, n_times); }
  191. std::string name() override { PYBIND11_OVERLOAD(std::string, AnimalBase, name, ); }
  192. };
  193. template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
  194. using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
  195. // Override PyAnimal's pure virtual go() with a non-pure one:
  196. std::string go(int n_times) override { PYBIND11_OVERLOAD(std::string, DogBase, go, n_times); }
  197. std::string bark() override { PYBIND11_OVERLOAD(std::string, DogBase, bark, ); }
  198. };
  199. This technique has the advantage of requiring just one trampoline method to be
  200. declared per virtual method and pure virtual method override. It does,
  201. however, require the compiler to generate at least as many methods (and
  202. possibly more, if both pure virtual and overridden pure virtual methods are
  203. exposed, as above).
  204. The classes are then registered with pybind11 using:
  205. .. code-block:: cpp
  206. py::class_<Animal, PyAnimal<>> animal(m, "Animal");
  207. py::class_<Dog, PyDog<>> dog(m, "Dog");
  208. py::class_<Husky, PyDog<Husky>> husky(m, "Husky");
  209. // ... add animal, dog, husky definitions
  210. Note that ``Husky`` did not require a dedicated trampoline template class at
  211. all, since it neither declares any new virtual methods nor provides any pure
  212. virtual method implementations.
  213. With either the repeated-virtuals or templated trampoline methods in place, you
  214. can now create a python class that inherits from ``Dog``:
  215. .. code-block:: python
  216. class ShihTzu(Dog):
  217. def bark(self):
  218. return "yip!"
  219. .. seealso::
  220. See the file :file:`tests/test_virtual_functions.cpp` for complete examples
  221. using both the duplication and templated trampoline approaches.
  222. Extended trampoline class functionality
  223. =======================================
  224. The trampoline classes described in the previous sections are, by default, only
  225. initialized when needed. More specifically, they are initialized when a python
  226. class actually inherits from a registered type (instead of merely creating an
  227. instance of the registered type), or when a registered constructor is only
  228. valid for the trampoline class but not the registered class. This is primarily
  229. for performance reasons: when the trampoline class is not needed for anything
  230. except virtual method dispatching, not initializing the trampoline class
  231. improves performance by avoiding needing to do a run-time check to see if the
  232. inheriting python instance has an overloaded method.
  233. Sometimes, however, it is useful to always initialize a trampoline class as an
  234. intermediate class that does more than just handle virtual method dispatching.
  235. For example, such a class might perform extra class initialization, extra
  236. destruction operations, and might define new members and methods to enable a
  237. more python-like interface to a class.
  238. In order to tell pybind11 that it should *always* initialize the trampoline
  239. class when creating new instances of a type, the class constructors should be
  240. declared using ``py::init_alias<Args, ...>()`` instead of the usual
  241. ``py::init<Args, ...>()``. This forces construction via the trampoline class,
  242. ensuring member initialization and (eventual) destruction.
  243. .. seealso::
  244. See the file :file:`tests/test_alias_initialization.cpp` for complete examples
  245. showing both normal and forced trampoline instantiation.
  246. .. _custom_constructors:
  247. Custom constructors
  248. ===================
  249. The syntax for binding constructors was previously introduced, but it only
  250. works when a constructor with the given parameters actually exists on the C++
  251. side. To extend this to more general cases, let's take a look at what actually
  252. happens under the hood: the following statement
  253. .. code-block:: cpp
  254. py::class_<Example>(m, "Example")
  255. .def(py::init<int>());
  256. is short hand notation for
  257. .. code-block:: cpp
  258. py::class_<Example>(m, "Example")
  259. .def("__init__",
  260. [](Example &instance, int arg) {
  261. new (&instance) Example(arg);
  262. }
  263. );
  264. In other words, :func:`init` creates an anonymous function that invokes an
  265. in-place constructor. Memory allocation etc. is already take care of beforehand
  266. within pybind11.
  267. .. _classes_with_non_public_destructors:
  268. Non-public destructors
  269. ======================
  270. If a class has a private or protected destructor (as might e.g. be the case in
  271. a singleton pattern), a compile error will occur when creating bindings via
  272. pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
  273. is responsible for managing the lifetime of instances will reference the
  274. destructor even if no deallocations ever take place. In order to expose classes
  275. with private or protected destructors, it is possible to override the holder
  276. type via a holder type argument to ``class_``. Pybind11 provides a helper class
  277. ``py::nodelete`` that disables any destructor invocations. In this case, it is
  278. crucial that instances are deallocated on the C++ side to avoid memory leaks.
  279. .. code-block:: cpp
  280. /* ... definition ... */
  281. class MyClass {
  282. private:
  283. ~MyClass() { }
  284. };
  285. /* ... binding code ... */
  286. py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
  287. .def(py::init<>)
  288. Implicit conversions
  289. ====================
  290. Suppose that instances of two types ``A`` and ``B`` are used in a project, and
  291. that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
  292. could be a fixed and an arbitrary precision number type).
  293. .. code-block:: cpp
  294. py::class_<A>(m, "A")
  295. /// ... members ...
  296. py::class_<B>(m, "B")
  297. .def(py::init<A>())
  298. /// ... members ...
  299. m.def("func",
  300. [](const B &) { /* .... */ }
  301. );
  302. To invoke the function ``func`` using a variable ``a`` containing an ``A``
  303. instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
  304. will automatically apply an implicit type conversion, which makes it possible
  305. to directly write ``func(a)``.
  306. In this situation (i.e. where ``B`` has a constructor that converts from
  307. ``A``), the following statement enables similar implicit conversions on the
  308. Python side:
  309. .. code-block:: cpp
  310. py::implicitly_convertible<A, B>();
  311. .. note::
  312. Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
  313. data type that is exposed to Python via pybind11.
  314. .. _static_properties:
  315. Static properties
  316. =================
  317. The section on :ref:`properties` discussed the creation of instance properties
  318. that are implemented in terms of C++ getters and setters.
  319. Static properties can also be created in a similar way to expose getters and
  320. setters of static class attributes. It is important to note that the implicit
  321. ``self`` argument also exists in this case and is used to pass the Python
  322. ``type`` subclass instance. This parameter will often not be needed by the C++
  323. side, and the following example illustrates how to instantiate a lambda getter
  324. function that ignores it:
  325. .. code-block:: cpp
  326. py::class_<Foo>(m, "Foo")
  327. .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
  328. Operator overloading
  329. ====================
  330. Suppose that we're given the following ``Vector2`` class with a vector addition
  331. and scalar multiplication operation, all implemented using overloaded operators
  332. in C++.
  333. .. code-block:: cpp
  334. class Vector2 {
  335. public:
  336. Vector2(float x, float y) : x(x), y(y) { }
  337. Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
  338. Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
  339. Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
  340. Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
  341. friend Vector2 operator*(float f, const Vector2 &v) {
  342. return Vector2(f * v.x, f * v.y);
  343. }
  344. std::string toString() const {
  345. return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
  346. }
  347. private:
  348. float x, y;
  349. };
  350. The following snippet shows how the above operators can be conveniently exposed
  351. to Python.
  352. .. code-block:: cpp
  353. #include <pybind11/operators.h>
  354. PYBIND11_PLUGIN(example) {
  355. py::module m("example", "pybind11 example plugin");
  356. py::class_<Vector2>(m, "Vector2")
  357. .def(py::init<float, float>())
  358. .def(py::self + py::self)
  359. .def(py::self += py::self)
  360. .def(py::self *= float())
  361. .def(float() * py::self)
  362. .def("__repr__", &Vector2::toString);
  363. return m.ptr();
  364. }
  365. Note that a line like
  366. .. code-block:: cpp
  367. .def(py::self * float())
  368. is really just short hand notation for
  369. .. code-block:: cpp
  370. .def("__mul__", [](const Vector2 &a, float b) {
  371. return a * b;
  372. }, py::is_operator())
  373. This can be useful for exposing additional operators that don't exist on the
  374. C++ side, or to perform other types of customization. The ``py::is_operator``
  375. flag marker is needed to inform pybind11 that this is an operator, which
  376. returns ``NotImplemented`` when invoked with incompatible arguments rather than
  377. throwing a type error.
  378. .. note::
  379. To use the more convenient ``py::self`` notation, the additional
  380. header file :file:`pybind11/operators.h` must be included.
  381. .. seealso::
  382. The file :file:`tests/test_operator_overloading.cpp` contains a
  383. complete example that demonstrates how to work with overloaded operators in
  384. more detail.
  385. Pickling support
  386. ================
  387. Python's ``pickle`` module provides a powerful facility to serialize and
  388. de-serialize a Python object graph into a binary data stream. To pickle and
  389. unpickle C++ classes using pybind11, two additional functions must be provided.
  390. Suppose the class in question has the following signature:
  391. .. code-block:: cpp
  392. class Pickleable {
  393. public:
  394. Pickleable(const std::string &value) : m_value(value) { }
  395. const std::string &value() const { return m_value; }
  396. void setExtra(int extra) { m_extra = extra; }
  397. int extra() const { return m_extra; }
  398. private:
  399. std::string m_value;
  400. int m_extra = 0;
  401. };
  402. The binding code including the requisite ``__setstate__`` and ``__getstate__`` methods [#f3]_
  403. looks as follows:
  404. .. code-block:: cpp
  405. py::class_<Pickleable>(m, "Pickleable")
  406. .def(py::init<std::string>())
  407. .def("value", &Pickleable::value)
  408. .def("extra", &Pickleable::extra)
  409. .def("setExtra", &Pickleable::setExtra)
  410. .def("__getstate__", [](const Pickleable &p) {
  411. /* Return a tuple that fully encodes the state of the object */
  412. return py::make_tuple(p.value(), p.extra());
  413. })
  414. .def("__setstate__", [](Pickleable &p, py::tuple t) {
  415. if (t.size() != 2)
  416. throw std::runtime_error("Invalid state!");
  417. /* Invoke the in-place constructor. Note that this is needed even
  418. when the object just has a trivial default constructor */
  419. new (&p) Pickleable(t[0].cast<std::string>());
  420. /* Assign any additional state */
  421. p.setExtra(t[1].cast<int>());
  422. });
  423. An instance can now be pickled as follows:
  424. .. code-block:: python
  425. try:
  426. import cPickle as pickle # Use cPickle on Python 2.7
  427. except ImportError:
  428. import pickle
  429. p = Pickleable("test_value")
  430. p.setExtra(15)
  431. data = pickle.dumps(p, 2)
  432. Note that only the cPickle module is supported on Python 2.7. The second
  433. argument to ``dumps`` is also crucial: it selects the pickle protocol version
  434. 2, since the older version 1 is not supported. Newer versions are also fine—for
  435. instance, specify ``-1`` to always use the latest available version. Beware:
  436. failure to follow these instructions will cause important pybind11 memory
  437. allocation routines to be skipped during unpickling, which will likely lead to
  438. memory corruption and/or segmentation faults.
  439. .. seealso::
  440. The file :file:`tests/test_pickling.cpp` contains a complete example
  441. that demonstrates how to pickle and unpickle types using pybind11 in more
  442. detail.
  443. .. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
  444. Multiple Inheritance
  445. ====================
  446. pybind11 can create bindings for types that derive from multiple base types
  447. (aka. *multiple inheritance*). To do so, specify all bases in the template
  448. arguments of the ``class_`` declaration:
  449. .. code-block:: cpp
  450. py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
  451. ...
  452. The base types can be specified in arbitrary order, and they can even be
  453. interspersed with alias types and holder types (discussed earlier in this
  454. document)---pybind11 will automatically find out which is which. The only
  455. requirement is that the first template argument is the type to be declared.
  456. There are two caveats regarding the implementation of this feature:
  457. 1. When only one base type is specified for a C++ type that actually has
  458. multiple bases, pybind11 will assume that it does not participate in
  459. multiple inheritance, which can lead to undefined behavior. In such cases,
  460. add the tag ``multiple_inheritance``:
  461. .. code-block:: cpp
  462. py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
  463. The tag is redundant and does not need to be specified when multiple base
  464. types are listed.
  465. 2. As was previously discussed in the section on :ref:`overriding_virtuals`, it
  466. is easy to create Python types that derive from C++ classes. It is even
  467. possible to make use of multiple inheritance to declare a Python class which
  468. has e.g. a C++ and a Python class as bases. However, any attempt to create a
  469. type that has *two or more* C++ classes in its hierarchy of base types will
  470. fail with a fatal error message: ``TypeError: multiple bases have instance
  471. lay-out conflict``. Core Python types that are implemented in C (e.g.
  472. ``dict``, ``list``, ``Exception``, etc.) also fall under this combination
  473. and cannot be combined with C++ types bound using pybind11 via multiple
  474. inheritance.