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