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.

637 lines
22 KiB

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