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.

657 lines
23 KiB

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