Back to home page

EIC code displayed by LXR

 
 

    


Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/advanced/classes.rst is written in an unsupported language. File is not indexed.

0001 Classes
0002 #######
0003 
0004 This section presents advanced binding code for classes and it is assumed
0005 that you are already familiar with the basics from :doc:`/classes`.
0006 
0007 .. _overriding_virtuals:
0008 
0009 Overriding virtual functions in Python
0010 ======================================
0011 
0012 Suppose that a C++ class or interface has a virtual function that we'd like
0013 to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is
0014 given as a specific example of how one would do this with traditional C++
0015 code).
0016 
0017 .. code-block:: cpp
0018 
0019     class Animal {
0020     public:
0021         virtual ~Animal() { }
0022         virtual std::string go(int n_times) = 0;
0023     };
0024 
0025     class Dog : public Animal {
0026     public:
0027         std::string go(int n_times) override {
0028             std::string result;
0029             for (int i=0; i<n_times; ++i)
0030                 result += "woof! ";
0031             return result;
0032         }
0033     };
0034 
0035 Let's also suppose that we are given a plain function which calls the
0036 function ``go()`` on an arbitrary ``Animal`` instance.
0037 
0038 .. code-block:: cpp
0039 
0040     std::string call_go(Animal *animal) {
0041         return animal->go(3);
0042     }
0043 
0044 Normally, the binding code for these classes would look as follows:
0045 
0046 .. code-block:: cpp
0047 
0048     PYBIND11_MODULE(example, m) {
0049         py::class_<Animal>(m, "Animal")
0050             .def("go", &Animal::go);
0051 
0052         py::class_<Dog, Animal>(m, "Dog")
0053             .def(py::init<>());
0054 
0055         m.def("call_go", &call_go);
0056     }
0057 
0058 However, these bindings are impossible to extend: ``Animal`` is not
0059 constructible, and we clearly require some kind of "trampoline" that
0060 redirects virtual calls back to Python.
0061 
0062 Defining a new type of ``Animal`` from within Python is possible but requires a
0063 helper class that is defined as follows:
0064 
0065 .. code-block:: cpp
0066 
0067     class PyAnimal : public Animal {
0068     public:
0069         /* Inherit the constructors */
0070         using Animal::Animal;
0071 
0072         /* Trampoline (need one for each virtual function) */
0073         std::string go(int n_times) override {
0074             PYBIND11_OVERRIDE_PURE(
0075                 std::string, /* Return type */
0076                 Animal,      /* Parent class */
0077                 go,          /* Name of function in C++ (must match Python name) */
0078                 n_times      /* Argument(s) */
0079             );
0080         }
0081     };
0082 
0083 The macro :c:macro:`PYBIND11_OVERRIDE_PURE` should be used for pure virtual
0084 functions, and :c:macro:`PYBIND11_OVERRIDE` should be used for functions which have
0085 a default implementation.  There are also two alternate macros
0086 :c:macro:`PYBIND11_OVERRIDE_PURE_NAME` and :c:macro:`PYBIND11_OVERRIDE_NAME` which
0087 take a string-valued name argument between the *Parent class* and *Name of the
0088 function* slots, which defines the name of function in Python. This is required
0089 when the C++ and Python versions of the
0090 function have different names, e.g.  ``operator()`` vs ``__call__``.
0091 
0092 The binding code also needs a few minor adaptations (highlighted):
0093 
0094 .. code-block:: cpp
0095     :emphasize-lines: 2,3
0096 
0097     PYBIND11_MODULE(example, m) {
0098         py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal")
0099             .def(py::init<>())
0100             .def("go", &Animal::go);
0101 
0102         py::class_<Dog, Animal>(m, "Dog")
0103             .def(py::init<>());
0104 
0105         m.def("call_go", &call_go);
0106     }
0107 
0108 Importantly, pybind11 is made aware of the trampoline helper class by
0109 specifying it as an extra template argument to :class:`class_`. (This can also
0110 be combined with other template arguments such as a custom holder type; the
0111 order of template types does not matter).  Following this, we are able to
0112 define a constructor as usual.
0113 
0114 Bindings should be made against the actual class, not the trampoline helper class.
0115 
0116 .. code-block:: cpp
0117     :emphasize-lines: 3
0118 
0119     py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal");
0120         .def(py::init<>())
0121         .def("go", &PyAnimal::go); /* <--- THIS IS WRONG, use &Animal::go */
0122 
0123 Note, however, that the above is sufficient for allowing python classes to
0124 extend ``Animal``, but not ``Dog``: see :ref:`virtual_and_inheritance` for the
0125 necessary steps required to providing proper overriding support for inherited
0126 classes.
0127 
0128 The Python session below shows how to override ``Animal::go`` and invoke it via
0129 a virtual method call.
0130 
0131 .. code-block:: pycon
0132 
0133     >>> from example import *
0134     >>> d = Dog()
0135     >>> call_go(d)
0136     'woof! woof! woof! '
0137     >>> class Cat(Animal):
0138     ...     def go(self, n_times):
0139     ...         return "meow! " * n_times
0140     ...
0141     >>> c = Cat()
0142     >>> call_go(c)
0143     'meow! meow! meow! '
0144 
0145 If you are defining a custom constructor in a derived Python class, you *must*
0146 ensure that you explicitly call the bound C++ constructor using ``__init__``,
0147 *regardless* of whether it is a default constructor or not. Otherwise, the
0148 memory for the C++ portion of the instance will be left uninitialized, which
0149 will generally leave the C++ instance in an invalid state and cause undefined
0150 behavior if the C++ instance is subsequently used.
0151 
0152 .. versionchanged:: 2.6
0153    The default pybind11 metaclass will throw a ``TypeError`` when it detects
0154    that ``__init__`` was not called by a derived class.
0155 
0156 Here is an example:
0157 
0158 .. code-block:: python
0159 
0160     class Dachshund(Dog):
0161         def __init__(self, name):
0162             Dog.__init__(self)  # Without this, a TypeError is raised.
0163             self.name = name
0164 
0165         def bark(self):
0166             return "yap!"
0167 
0168 Note that a direct ``__init__`` constructor *should be called*, and ``super()``
0169 should not be used. For simple cases of linear inheritance, ``super()``
0170 may work, but once you begin mixing Python and C++ multiple inheritance,
0171 things will fall apart due to differences between Python's MRO and C++'s
0172 mechanisms.
0173 
0174 Please take a look at the :ref:`macro_notes` before using this feature.
0175 
0176 .. note::
0177 
0178     When the overridden type returns a reference or pointer to a type that
0179     pybind11 converts from Python (for example, numeric values, std::string,
0180     and other built-in value-converting types), there are some limitations to
0181     be aware of:
0182 
0183     - because in these cases there is no C++ variable to reference (the value
0184       is stored in the referenced Python variable), pybind11 provides one in
0185       the PYBIND11_OVERRIDE macros (when needed) with static storage duration.
0186       Note that this means that invoking the overridden method on *any*
0187       instance will change the referenced value stored in *all* instances of
0188       that type.
0189 
0190     - Attempts to modify a non-const reference will not have the desired
0191       effect: it will change only the static cache variable, but this change
0192       will not propagate to underlying Python instance, and the change will be
0193       replaced the next time the override is invoked.
0194 
0195 .. warning::
0196 
0197     The :c:macro:`PYBIND11_OVERRIDE` and accompanying macros used to be called
0198     ``PYBIND11_OVERLOAD`` up until pybind11 v2.5.0, and :func:`get_override`
0199     used to be called ``get_overload``. This naming was corrected and the older
0200     macro and function names may soon be deprecated, in order to reduce
0201     confusion with overloaded functions and methods and ``py::overload_cast``
0202     (see :ref:`classes`).
0203 
0204 .. seealso::
0205 
0206     The file :file:`tests/test_virtual_functions.cpp` contains a complete
0207     example that demonstrates how to override virtual functions using pybind11
0208     in more detail.
0209 
0210 .. _virtual_and_inheritance:
0211 
0212 Combining virtual functions and inheritance
0213 ===========================================
0214 
0215 When combining virtual methods with inheritance, you need to be sure to provide
0216 an override for each method for which you want to allow overrides from derived
0217 python classes.  For example, suppose we extend the above ``Animal``/``Dog``
0218 example as follows:
0219 
0220 .. code-block:: cpp
0221 
0222     class Animal {
0223     public:
0224         virtual std::string go(int n_times) = 0;
0225         virtual std::string name() { return "unknown"; }
0226     };
0227     class Dog : public Animal {
0228     public:
0229         std::string go(int n_times) override {
0230             std::string result;
0231             for (int i=0; i<n_times; ++i)
0232                 result += bark() + " ";
0233             return result;
0234         }
0235         virtual std::string bark() { return "woof!"; }
0236     };
0237 
0238 then the trampoline class for ``Animal`` must, as described in the previous
0239 section, override ``go()`` and ``name()``, but in order to allow python code to
0240 inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
0241 overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
0242 methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
0243 override the ``name()`` method):
0244 
0245 .. code-block:: cpp
0246 
0247     class PyAnimal : public Animal {
0248     public:
0249         using Animal::Animal; // Inherit constructors
0250         std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Animal, go, n_times); }
0251         std::string name() override { PYBIND11_OVERRIDE(std::string, Animal, name, ); }
0252     };
0253     class PyDog : public Dog {
0254     public:
0255         using Dog::Dog; // Inherit constructors
0256         std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, Dog, go, n_times); }
0257         std::string name() override { PYBIND11_OVERRIDE(std::string, Dog, name, ); }
0258         std::string bark() override { PYBIND11_OVERRIDE(std::string, Dog, bark, ); }
0259     };
0260 
0261 .. note::
0262 
0263     Note the trailing commas in the ``PYBIND11_OVERRIDE`` calls to ``name()``
0264     and ``bark()``. These are needed to portably implement a trampoline for a
0265     function that does not take any arguments. For functions that take
0266     a nonzero number of arguments, the trailing comma must be omitted.
0267 
0268 A registered class derived from a pybind11-registered class with virtual
0269 methods requires a similar trampoline class, *even if* it doesn't explicitly
0270 declare or override any virtual methods itself:
0271 
0272 .. code-block:: cpp
0273 
0274     class Husky : public Dog {};
0275     class PyHusky : public Husky {
0276     public:
0277         using Husky::Husky; // Inherit constructors
0278         std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Husky, go, n_times); }
0279         std::string name() override { PYBIND11_OVERRIDE(std::string, Husky, name, ); }
0280         std::string bark() override { PYBIND11_OVERRIDE(std::string, Husky, bark, ); }
0281     };
0282 
0283 There is, however, a technique that can be used to avoid this duplication
0284 (which can be especially helpful for a base class with several virtual
0285 methods).  The technique involves using template trampoline classes, as
0286 follows:
0287 
0288 .. code-block:: cpp
0289 
0290     template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
0291     public:
0292         using AnimalBase::AnimalBase; // Inherit constructors
0293         std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, AnimalBase, go, n_times); }
0294         std::string name() override { PYBIND11_OVERRIDE(std::string, AnimalBase, name, ); }
0295     };
0296     template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
0297     public:
0298         using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
0299         // Override PyAnimal's pure virtual go() with a non-pure one:
0300         std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, DogBase, go, n_times); }
0301         std::string bark() override { PYBIND11_OVERRIDE(std::string, DogBase, bark, ); }
0302     };
0303 
0304 This technique has the advantage of requiring just one trampoline method to be
0305 declared per virtual method and pure virtual method override.  It does,
0306 however, require the compiler to generate at least as many methods (and
0307 possibly more, if both pure virtual and overridden pure virtual methods are
0308 exposed, as above).
0309 
0310 The classes are then registered with pybind11 using:
0311 
0312 .. code-block:: cpp
0313 
0314     py::class_<Animal, PyAnimal<>> animal(m, "Animal");
0315     py::class_<Dog, Animal, PyDog<>> dog(m, "Dog");
0316     py::class_<Husky, Dog, PyDog<Husky>> husky(m, "Husky");
0317     // ... add animal, dog, husky definitions
0318 
0319 Note that ``Husky`` did not require a dedicated trampoline template class at
0320 all, since it neither declares any new virtual methods nor provides any pure
0321 virtual method implementations.
0322 
0323 With either the repeated-virtuals or templated trampoline methods in place, you
0324 can now create a python class that inherits from ``Dog``:
0325 
0326 .. code-block:: python
0327 
0328     class ShihTzu(Dog):
0329         def bark(self):
0330             return "yip!"
0331 
0332 .. seealso::
0333 
0334     See the file :file:`tests/test_virtual_functions.cpp` for complete examples
0335     using both the duplication and templated trampoline approaches.
0336 
0337 .. _extended_aliases:
0338 
0339 Extended trampoline class functionality
0340 =======================================
0341 
0342 .. _extended_class_functionality_forced_trampoline:
0343 
0344 Forced trampoline class initialisation
0345 --------------------------------------
0346 The trampoline classes described in the previous sections are, by default, only
0347 initialized when needed.  More specifically, they are initialized when a python
0348 class actually inherits from a registered type (instead of merely creating an
0349 instance of the registered type), or when a registered constructor is only
0350 valid for the trampoline class but not the registered class.  This is primarily
0351 for performance reasons: when the trampoline class is not needed for anything
0352 except virtual method dispatching, not initializing the trampoline class
0353 improves performance by avoiding needing to do a run-time check to see if the
0354 inheriting python instance has an overridden method.
0355 
0356 Sometimes, however, it is useful to always initialize a trampoline class as an
0357 intermediate class that does more than just handle virtual method dispatching.
0358 For example, such a class might perform extra class initialization, extra
0359 destruction operations, and might define new members and methods to enable a
0360 more python-like interface to a class.
0361 
0362 In order to tell pybind11 that it should *always* initialize the trampoline
0363 class when creating new instances of a type, the class constructors should be
0364 declared using ``py::init_alias<Args, ...>()`` instead of the usual
0365 ``py::init<Args, ...>()``.  This forces construction via the trampoline class,
0366 ensuring member initialization and (eventual) destruction.
0367 
0368 .. seealso::
0369 
0370     See the file :file:`tests/test_virtual_functions.cpp` for complete examples
0371     showing both normal and forced trampoline instantiation.
0372 
0373 Different method signatures
0374 ---------------------------
0375 The macro's introduced in :ref:`overriding_virtuals` cover most of the standard
0376 use cases when exposing C++ classes to Python. Sometimes it is hard or unwieldy
0377 to create a direct one-on-one mapping between the arguments and method return
0378 type.
0379 
0380 An example would be when the C++ signature contains output arguments using
0381 references (See also :ref:`faq_reference_arguments`). Another way of solving
0382 this is to use the method body of the trampoline class to do conversions to the
0383 input and return of the Python method.
0384 
0385 The main building block to do so is the :func:`get_override`, this function
0386 allows retrieving a method implemented in Python from within the trampoline's
0387 methods. Consider for example a C++ method which has the signature
0388 ``bool myMethod(int32_t& value)``, where the return indicates whether
0389 something should be done with the ``value``. This can be made convenient on the
0390 Python side by allowing the Python function to return ``None`` or an ``int``:
0391 
0392 .. code-block:: cpp
0393 
0394     bool MyClass::myMethod(int32_t& value)
0395     {
0396         pybind11::gil_scoped_acquire gil;  // Acquire the GIL while in this scope.
0397         // Try to look up the overridden method on the Python side.
0398         pybind11::function override = pybind11::get_override(this, "myMethod");
0399         if (override) {  // method is found
0400             auto obj = override(value);  // Call the Python function.
0401             if (py::isinstance<py::int_>(obj)) {  // check if it returned a Python integer type
0402                 value = obj.cast<int32_t>();  // Cast it and assign it to the value.
0403                 return true;  // Return true; value should be used.
0404             } else {
0405                 return false;  // Python returned none, return false.
0406             }
0407         }
0408         return false;  // Alternatively return MyClass::myMethod(value);
0409     }
0410 
0411 
0412 .. _custom_constructors:
0413 
0414 Custom constructors
0415 ===================
0416 
0417 The syntax for binding constructors was previously introduced, but it only
0418 works when a constructor of the appropriate arguments actually exists on the
0419 C++ side.  To extend this to more general cases, pybind11 makes it possible
0420 to bind factory functions as constructors. For example, suppose you have a
0421 class like this:
0422 
0423 .. code-block:: cpp
0424 
0425     class Example {
0426     private:
0427         Example(int); // private constructor
0428     public:
0429         // Factory function:
0430         static Example create(int a) { return Example(a); }
0431     };
0432 
0433     py::class_<Example>(m, "Example")
0434         .def(py::init(&Example::create));
0435 
0436 While it is possible to create a straightforward binding of the static
0437 ``create`` method, it may sometimes be preferable to expose it as a constructor
0438 on the Python side. This can be accomplished by calling ``.def(py::init(...))``
0439 with the function reference returning the new instance passed as an argument.
0440 It is also possible to use this approach to bind a function returning a new
0441 instance by raw pointer or by the holder (e.g. ``std::unique_ptr``).
0442 
0443 The following example shows the different approaches:
0444 
0445 .. code-block:: cpp
0446 
0447     class Example {
0448     private:
0449         Example(int); // private constructor
0450     public:
0451         // Factory function - returned by value:
0452         static Example create(int a) { return Example(a); }
0453 
0454         // These constructors are publicly callable:
0455         Example(double);
0456         Example(int, int);
0457         Example(std::string);
0458     };
0459 
0460     py::class_<Example>(m, "Example")
0461         // Bind the factory function as a constructor:
0462         .def(py::init(&Example::create))
0463         // Bind a lambda function returning a pointer wrapped in a holder:
0464         .def(py::init([](std::string arg) {
0465             return std::unique_ptr<Example>(new Example(arg));
0466         }))
0467         // Return a raw pointer:
0468         .def(py::init([](int a, int b) { return new Example(a, b); }))
0469         // You can mix the above with regular C++ constructor bindings as well:
0470         .def(py::init<double>())
0471         ;
0472 
0473 When the constructor is invoked from Python, pybind11 will call the factory
0474 function and store the resulting C++ instance in the Python instance.
0475 
0476 When combining factory functions constructors with :ref:`virtual function
0477 trampolines <overriding_virtuals>` there are two approaches.  The first is to
0478 add a constructor to the alias class that takes a base value by
0479 rvalue-reference.  If such a constructor is available, it will be used to
0480 construct an alias instance from the value returned by the factory function.
0481 The second option is to provide two factory functions to ``py::init()``: the
0482 first will be invoked when no alias class is required (i.e. when the class is
0483 being used but not inherited from in Python), and the second will be invoked
0484 when an alias is required.
0485 
0486 You can also specify a single factory function that always returns an alias
0487 instance: this will result in behaviour similar to ``py::init_alias<...>()``,
0488 as described in the :ref:`extended trampoline class documentation
0489 <extended_aliases>`.
0490 
0491 The following example shows the different factory approaches for a class with
0492 an alias:
0493 
0494 .. code-block:: cpp
0495 
0496     #include <pybind11/factory.h>
0497     class Example {
0498     public:
0499         // ...
0500         virtual ~Example() = default;
0501     };
0502     class PyExample : public Example {
0503     public:
0504         using Example::Example;
0505         PyExample(Example &&base) : Example(std::move(base)) {}
0506     };
0507     py::class_<Example, PyExample>(m, "Example")
0508         // Returns an Example pointer.  If a PyExample is needed, the Example
0509         // instance will be moved via the extra constructor in PyExample, above.
0510         .def(py::init([]() { return new Example(); }))
0511         // Two callbacks:
0512         .def(py::init([]() { return new Example(); } /* no alias needed */,
0513                       []() { return new PyExample(); } /* alias needed */))
0514         // *Always* returns an alias instance (like py::init_alias<>())
0515         .def(py::init([]() { return new PyExample(); }))
0516         ;
0517 
0518 Brace initialization
0519 --------------------
0520 
0521 ``pybind11::init<>`` internally uses C++11 brace initialization to call the
0522 constructor of the target class. This means that it can be used to bind
0523 *implicit* constructors as well:
0524 
0525 .. code-block:: cpp
0526 
0527     struct Aggregate {
0528         int a;
0529         std::string b;
0530     };
0531 
0532     py::class_<Aggregate>(m, "Aggregate")
0533         .def(py::init<int, const std::string &>());
0534 
0535 .. note::
0536 
0537     Note that brace initialization preferentially invokes constructor overloads
0538     taking a ``std::initializer_list``. In the rare event that this causes an
0539     issue, you can work around it by using ``py::init(...)`` with a lambda
0540     function that constructs the new object as desired.
0541 
0542 .. _classes_with_non_public_destructors:
0543 
0544 Non-public destructors
0545 ======================
0546 
0547 If a class has a private or protected destructor (as might e.g. be the case in
0548 a singleton pattern), a compile error will occur when creating bindings via
0549 pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
0550 is responsible for managing the lifetime of instances will reference the
0551 destructor even if no deallocations ever take place. In order to expose classes
0552 with private or protected destructors, it is possible to override the holder
0553 type via a holder type argument to ``class_``. Pybind11 provides a helper class
0554 ``py::nodelete`` that disables any destructor invocations. In this case, it is
0555 crucial that instances are deallocated on the C++ side to avoid memory leaks.
0556 
0557 .. code-block:: cpp
0558 
0559     /* ... definition ... */
0560 
0561     class MyClass {
0562     private:
0563         ~MyClass() { }
0564     };
0565 
0566     /* ... binding code ... */
0567 
0568     py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
0569         .def(py::init<>())
0570 
0571 .. _destructors_that_call_python:
0572 
0573 Destructors that call Python
0574 ============================
0575 
0576 If a Python function is invoked from a C++ destructor, an exception may be thrown
0577 of type :class:`error_already_set`. If this error is thrown out of a class destructor,
0578 ``std::terminate()`` will be called, terminating the process. Class destructors
0579 must catch all exceptions of type :class:`error_already_set` to discard the Python
0580 exception using :func:`error_already_set::discard_as_unraisable`.
0581 
0582 Every Python function should be treated as *possibly throwing*. When a Python generator
0583 stops yielding items, Python will throw a ``StopIteration`` exception, which can pass
0584 though C++ destructors if the generator's stack frame holds the last reference to C++
0585 objects.
0586 
0587 For more information, see :ref:`the documentation on exceptions <unraisable_exceptions>`.
0588 
0589 .. code-block:: cpp
0590 
0591     class MyClass {
0592     public:
0593         ~MyClass() {
0594             try {
0595                 py::print("Even printing is dangerous in a destructor");
0596                 py::exec("raise ValueError('This is an unraisable exception')");
0597             } catch (py::error_already_set &e) {
0598                 // error_context should be information about where/why the occurred,
0599                 // e.g. use __func__ to get the name of the current function
0600                 e.discard_as_unraisable(__func__);
0601             }
0602         }
0603     };
0604 
0605 .. note::
0606 
0607     pybind11 does not support C++ destructors marked ``noexcept(false)``.
0608 
0609 .. versionadded:: 2.6
0610 
0611 .. _implicit_conversions:
0612 
0613 Implicit conversions
0614 ====================
0615 
0616 Suppose that instances of two types ``A`` and ``B`` are used in a project, and
0617 that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
0618 could be a fixed and an arbitrary precision number type).
0619 
0620 .. code-block:: cpp
0621 
0622     py::class_<A>(m, "A")
0623         /// ... members ...
0624 
0625     py::class_<B>(m, "B")
0626         .def(py::init<A>())
0627         /// ... members ...
0628 
0629     m.def("func",
0630         [](const B &) { /* .... */ }
0631     );
0632 
0633 To invoke the function ``func`` using a variable ``a`` containing an ``A``
0634 instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
0635 will automatically apply an implicit type conversion, which makes it possible
0636 to directly write ``func(a)``.
0637 
0638 In this situation (i.e. where ``B`` has a constructor that converts from
0639 ``A``), the following statement enables similar implicit conversions on the
0640 Python side:
0641 
0642 .. code-block:: cpp
0643 
0644     py::implicitly_convertible<A, B>();
0645 
0646 .. note::
0647 
0648     Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
0649     data type that is exposed to Python via pybind11.
0650 
0651     To prevent runaway recursion, implicit conversions are non-reentrant: an
0652     implicit conversion invoked as part of another implicit conversion of the
0653     same type (i.e. from ``A`` to ``B``) will fail.
0654 
0655 .. _static_properties:
0656 
0657 Static properties
0658 =================
0659 
0660 The section on :ref:`properties` discussed the creation of instance properties
0661 that are implemented in terms of C++ getters and setters.
0662 
0663 Static properties can also be created in a similar way to expose getters and
0664 setters of static class attributes. Note that the implicit ``self`` argument
0665 also exists in this case and is used to pass the Python ``type`` subclass
0666 instance. This parameter will often not be needed by the C++ side, and the
0667 following example illustrates how to instantiate a lambda getter function
0668 that ignores it:
0669 
0670 .. code-block:: cpp
0671 
0672     py::class_<Foo>(m, "Foo")
0673         .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
0674 
0675 Operator overloading
0676 ====================
0677 
0678 Suppose that we're given the following ``Vector2`` class with a vector addition
0679 and scalar multiplication operation, all implemented using overloaded operators
0680 in C++.
0681 
0682 .. code-block:: cpp
0683 
0684     class Vector2 {
0685     public:
0686         Vector2(float x, float y) : x(x), y(y) { }
0687 
0688         Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
0689         Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
0690         Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
0691         Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
0692 
0693         friend Vector2 operator*(float f, const Vector2 &v) {
0694             return Vector2(f * v.x, f * v.y);
0695         }
0696 
0697         std::string toString() const {
0698             return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
0699         }
0700     private:
0701         float x, y;
0702     };
0703 
0704 The following snippet shows how the above operators can be conveniently exposed
0705 to Python.
0706 
0707 .. code-block:: cpp
0708 
0709     #include <pybind11/operators.h>
0710 
0711     PYBIND11_MODULE(example, m) {
0712         py::class_<Vector2>(m, "Vector2")
0713             .def(py::init<float, float>())
0714             .def(py::self + py::self)
0715             .def(py::self += py::self)
0716             .def(py::self *= float())
0717             .def(float() * py::self)
0718             .def(py::self * float())
0719             .def(-py::self)
0720             .def("__repr__", &Vector2::toString);
0721     }
0722 
0723 Note that a line like
0724 
0725 .. code-block:: cpp
0726 
0727             .def(py::self * float())
0728 
0729 is really just short hand notation for
0730 
0731 .. code-block:: cpp
0732 
0733     .def("__mul__", [](const Vector2 &a, float b) {
0734         return a * b;
0735     }, py::is_operator())
0736 
0737 This can be useful for exposing additional operators that don't exist on the
0738 C++ side, or to perform other types of customization. The ``py::is_operator``
0739 flag marker is needed to inform pybind11 that this is an operator, which
0740 returns ``NotImplemented`` when invoked with incompatible arguments rather than
0741 throwing a type error.
0742 
0743 .. note::
0744 
0745     To use the more convenient ``py::self`` notation, the additional
0746     header file :file:`pybind11/operators.h` must be included.
0747 
0748 .. seealso::
0749 
0750     The file :file:`tests/test_operator_overloading.cpp` contains a
0751     complete example that demonstrates how to work with overloaded operators in
0752     more detail.
0753 
0754 .. _pickling:
0755 
0756 Pickling support
0757 ================
0758 
0759 Python's ``pickle`` module provides a powerful facility to serialize and
0760 de-serialize a Python object graph into a binary data stream. To pickle and
0761 unpickle C++ classes using pybind11, a ``py::pickle()`` definition must be
0762 provided. Suppose the class in question has the following signature:
0763 
0764 .. code-block:: cpp
0765 
0766     class Pickleable {
0767     public:
0768         Pickleable(const std::string &value) : m_value(value) { }
0769         const std::string &value() const { return m_value; }
0770 
0771         void setExtra(int extra) { m_extra = extra; }
0772         int extra() const { return m_extra; }
0773     private:
0774         std::string m_value;
0775         int m_extra = 0;
0776     };
0777 
0778 Pickling support in Python is enabled by defining the ``__setstate__`` and
0779 ``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()``
0780 to bind these two functions:
0781 
0782 .. code-block:: cpp
0783 
0784     py::class_<Pickleable>(m, "Pickleable")
0785         .def(py::init<std::string>())
0786         .def("value", &Pickleable::value)
0787         .def("extra", &Pickleable::extra)
0788         .def("setExtra", &Pickleable::setExtra)
0789         .def(py::pickle(
0790             [](const Pickleable &p) { // __getstate__
0791                 /* Return a tuple that fully encodes the state of the object */
0792                 return py::make_tuple(p.value(), p.extra());
0793             },
0794             [](py::tuple t) { // __setstate__
0795                 if (t.size() != 2)
0796                     throw std::runtime_error("Invalid state!");
0797 
0798                 /* Create a new C++ instance */
0799                 Pickleable p(t[0].cast<std::string>());
0800 
0801                 /* Assign any additional state */
0802                 p.setExtra(t[1].cast<int>());
0803 
0804                 return p;
0805             }
0806         ));
0807 
0808 The ``__setstate__`` part of the ``py::pickle()`` definition follows the same
0809 rules as the single-argument version of ``py::init()``. The return type can be
0810 a value, pointer or holder type. See :ref:`custom_constructors` for details.
0811 
0812 An instance can now be pickled as follows:
0813 
0814 .. code-block:: python
0815 
0816     import pickle
0817 
0818     p = Pickleable("test_value")
0819     p.setExtra(15)
0820     data = pickle.dumps(p)
0821 
0822 
0823 .. note::
0824     If given, the second argument to ``dumps`` must be 2 or larger - 0 and 1 are
0825     not supported. Newer versions are also fine; for instance, specify ``-1`` to
0826     always use the latest available version. Beware: failure to follow these
0827     instructions will cause important pybind11 memory allocation routines to be
0828     skipped during unpickling, which will likely lead to memory corruption
0829     and/or segmentation faults. Python defaults to version 3 (Python 3-3.7) and
0830     version 4 for Python 3.8+.
0831 
0832 .. seealso::
0833 
0834     The file :file:`tests/test_pickling.cpp` contains a complete example
0835     that demonstrates how to pickle and unpickle types using pybind11 in more
0836     detail.
0837 
0838 .. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
0839 
0840 Deepcopy support
0841 ================
0842 
0843 Python normally uses references in assignments. Sometimes a real copy is needed
0844 to prevent changing all copies. The ``copy`` module [#f5]_ provides these
0845 capabilities.
0846 
0847 A class with pickle support is automatically also (deep)copy
0848 compatible. However, performance can be improved by adding custom
0849 ``__copy__`` and ``__deepcopy__`` methods.
0850 
0851 For simple classes (deep)copy can be enabled by using the copy constructor,
0852 which should look as follows:
0853 
0854 .. code-block:: cpp
0855 
0856     py::class_<Copyable>(m, "Copyable")
0857         .def("__copy__",  [](const Copyable &self) {
0858             return Copyable(self);
0859         })
0860         .def("__deepcopy__", [](const Copyable &self, py::dict) {
0861             return Copyable(self);
0862         }, "memo"_a);
0863 
0864 .. note::
0865 
0866     Dynamic attributes will not be copied in this example.
0867 
0868 .. [#f5] https://docs.python.org/3/library/copy.html
0869 
0870 Multiple Inheritance
0871 ====================
0872 
0873 pybind11 can create bindings for types that derive from multiple base types
0874 (aka. *multiple inheritance*). To do so, specify all bases in the template
0875 arguments of the ``class_`` declaration:
0876 
0877 .. code-block:: cpp
0878 
0879     py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
0880        ...
0881 
0882 The base types can be specified in arbitrary order, and they can even be
0883 interspersed with alias types and holder types (discussed earlier in this
0884 document)---pybind11 will automatically find out which is which. The only
0885 requirement is that the first template argument is the type to be declared.
0886 
0887 It is also permitted to inherit multiply from exported C++ classes in Python,
0888 as well as inheriting from multiple Python and/or pybind11-exported classes.
0889 
0890 There is one caveat regarding the implementation of this feature:
0891 
0892 When only one base type is specified for a C++ type that actually has multiple
0893 bases, pybind11 will assume that it does not participate in multiple
0894 inheritance, which can lead to undefined behavior. In such cases, add the tag
0895 ``multiple_inheritance`` to the class constructor:
0896 
0897 .. code-block:: cpp
0898 
0899     py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
0900 
0901 The tag is redundant and does not need to be specified when multiple base types
0902 are listed.
0903 
0904 .. _module_local:
0905 
0906 Module-local class bindings
0907 ===========================
0908 
0909 When creating a binding for a class, pybind11 by default makes that binding
0910 "global" across modules.  What this means is that a type defined in one module
0911 can be returned from any module resulting in the same Python type.  For
0912 example, this allows the following:
0913 
0914 .. code-block:: cpp
0915 
0916     // In the module1.cpp binding code for module1:
0917     py::class_<Pet>(m, "Pet")
0918         .def(py::init<std::string>())
0919         .def_readonly("name", &Pet::name);
0920 
0921 .. code-block:: cpp
0922 
0923     // In the module2.cpp binding code for module2:
0924     m.def("create_pet", [](std::string name) { return new Pet(name); });
0925 
0926 .. code-block:: pycon
0927 
0928     >>> from module1 import Pet
0929     >>> from module2 import create_pet
0930     >>> pet1 = Pet("Kitty")
0931     >>> pet2 = create_pet("Doggy")
0932     >>> pet2.name()
0933     'Doggy'
0934 
0935 When writing binding code for a library, this is usually desirable: this
0936 allows, for example, splitting up a complex library into multiple Python
0937 modules.
0938 
0939 In some cases, however, this can cause conflicts.  For example, suppose two
0940 unrelated modules make use of an external C++ library and each provide custom
0941 bindings for one of that library's classes.  This will result in an error when
0942 a Python program attempts to import both modules (directly or indirectly)
0943 because of conflicting definitions on the external type:
0944 
0945 .. code-block:: cpp
0946 
0947     // dogs.cpp
0948 
0949     // Binding for external library class:
0950     py::class<pets::Pet>(m, "Pet")
0951         .def("name", &pets::Pet::name);
0952 
0953     // Binding for local extension class:
0954     py::class<Dog, pets::Pet>(m, "Dog")
0955         .def(py::init<std::string>());
0956 
0957 .. code-block:: cpp
0958 
0959     // cats.cpp, in a completely separate project from the above dogs.cpp.
0960 
0961     // Binding for external library class:
0962     py::class<pets::Pet>(m, "Pet")
0963         .def("get_name", &pets::Pet::name);
0964 
0965     // Binding for local extending class:
0966     py::class<Cat, pets::Pet>(m, "Cat")
0967         .def(py::init<std::string>());
0968 
0969 .. code-block:: pycon
0970 
0971     >>> import cats
0972     >>> import dogs
0973     Traceback (most recent call last):
0974       File "<stdin>", line 1, in <module>
0975     ImportError: generic_type: type "Pet" is already registered!
0976 
0977 To get around this, you can tell pybind11 to keep the external class binding
0978 localized to the module by passing the ``py::module_local()`` attribute into
0979 the ``py::class_`` constructor:
0980 
0981 .. code-block:: cpp
0982 
0983     // Pet binding in dogs.cpp:
0984     py::class<pets::Pet>(m, "Pet", py::module_local())
0985         .def("name", &pets::Pet::name);
0986 
0987 .. code-block:: cpp
0988 
0989     // Pet binding in cats.cpp:
0990     py::class<pets::Pet>(m, "Pet", py::module_local())
0991         .def("get_name", &pets::Pet::name);
0992 
0993 This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes,
0994 avoiding the conflict and allowing both modules to be loaded.  C++ code in the
0995 ``dogs`` module that casts or returns a ``Pet`` instance will result in a
0996 ``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result
0997 in a ``cats.Pet`` Python instance.
0998 
0999 This does come with two caveats, however: First, external modules cannot return
1000 or cast a ``Pet`` instance to Python (unless they also provide their own local
1001 bindings).  Second, from the Python point of view they are two distinct classes.
1002 
1003 Note that the locality only applies in the C++ -> Python direction.  When
1004 passing such a ``py::module_local`` type into a C++ function, the module-local
1005 classes are still considered.  This means that if the following function is
1006 added to any module (including but not limited to the ``cats`` and ``dogs``
1007 modules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet``
1008 argument:
1009 
1010 .. code-block:: cpp
1011 
1012     m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); });
1013 
1014 For example, suppose the above function is added to each of ``cats.cpp``,
1015 ``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that
1016 does *not* bind ``Pets`` at all).
1017 
1018 .. code-block:: pycon
1019 
1020     >>> import cats, dogs, frogs  # No error because of the added py::module_local()
1021     >>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover")
1022     >>> (cats.pet_name(mycat), dogs.pet_name(mydog))
1023     ('Fluffy', 'Rover')
1024     >>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat))
1025     ('Rover', 'Fluffy', 'Fluffy')
1026 
1027 It is possible to use ``py::module_local()`` registrations in one module even
1028 if another module registers the same type globally: within the module with the
1029 module-local definition, all C++ instances will be cast to the associated bound
1030 Python type.  In other modules any such values are converted to the global
1031 Python type created elsewhere.
1032 
1033 .. note::
1034 
1035     STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`
1036     header) apply ``py::module_local`` by default when the bound type might
1037     conflict with other modules; see :ref:`stl_bind` for details.
1038 
1039 .. note::
1040 
1041     The localization of the bound types is actually tied to the shared object
1042     or binary generated by the compiler/linker.  For typical modules created
1043     with ``PYBIND11_MODULE()``, this distinction is not significant.  It is
1044     possible, however, when :ref:`embedding` to embed multiple modules in the
1045     same binary (see :ref:`embedding_modules`).  In such a case, the
1046     localization will apply across all embedded modules within the same binary.
1047 
1048 .. seealso::
1049 
1050     The file :file:`tests/test_local_bindings.cpp` contains additional examples
1051     that demonstrate how ``py::module_local()`` works.
1052 
1053 Binding protected member functions
1054 ==================================
1055 
1056 It's normally not possible to expose ``protected`` member functions to Python:
1057 
1058 .. code-block:: cpp
1059 
1060     class A {
1061     protected:
1062         int foo() const { return 42; }
1063     };
1064 
1065     py::class_<A>(m, "A")
1066         .def("foo", &A::foo); // error: 'foo' is a protected member of 'A'
1067 
1068 On one hand, this is good because non-``public`` members aren't meant to be
1069 accessed from the outside. But we may want to make use of ``protected``
1070 functions in derived Python classes.
1071 
1072 The following pattern makes this possible:
1073 
1074 .. code-block:: cpp
1075 
1076     class A {
1077     protected:
1078         int foo() const { return 42; }
1079     };
1080 
1081     class Publicist : public A { // helper type for exposing protected functions
1082     public:
1083         using A::foo; // inherited with different access modifier
1084     };
1085 
1086     py::class_<A>(m, "A") // bind the primary class
1087         .def("foo", &Publicist::foo); // expose protected methods via the publicist
1088 
1089 This works because ``&Publicist::foo`` is exactly the same function as
1090 ``&A::foo`` (same signature and address), just with a different access
1091 modifier. The only purpose of the ``Publicist`` helper class is to make
1092 the function name ``public``.
1093 
1094 If the intent is to expose ``protected`` ``virtual`` functions which can be
1095 overridden in Python, the publicist pattern can be combined with the previously
1096 described trampoline:
1097 
1098 .. code-block:: cpp
1099 
1100     class A {
1101     public:
1102         virtual ~A() = default;
1103 
1104     protected:
1105         virtual int foo() const { return 42; }
1106     };
1107 
1108     class Trampoline : public A {
1109     public:
1110         int foo() const override { PYBIND11_OVERRIDE(int, A, foo, ); }
1111     };
1112 
1113     class Publicist : public A {
1114     public:
1115         using A::foo;
1116     };
1117 
1118     py::class_<A, Trampoline>(m, "A") // <-- `Trampoline` here
1119         .def("foo", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`!
1120 
1121 Binding final classes
1122 =====================
1123 
1124 Some classes may not be appropriate to inherit from. In C++11, classes can
1125 use the ``final`` specifier to ensure that a class cannot be inherited from.
1126 The ``py::is_final`` attribute can be used to ensure that Python classes
1127 cannot inherit from a specified type. The underlying C++ type does not need
1128 to be declared final.
1129 
1130 .. code-block:: cpp
1131 
1132     class IsFinal final {};
1133 
1134     py::class_<IsFinal>(m, "IsFinal", py::is_final());
1135 
1136 When you try to inherit from such a class in Python, you will now get this
1137 error:
1138 
1139 .. code-block:: pycon
1140 
1141     >>> class PyFinalChild(IsFinal):
1142     ...     pass
1143     ...
1144     TypeError: type 'IsFinal' is not an acceptable base type
1145 
1146 .. note:: This attribute is currently ignored on PyPy
1147 
1148 .. versionadded:: 2.6
1149 
1150 Binding classes with template parameters
1151 ========================================
1152 
1153 pybind11 can also wrap classes that have template parameters. Consider these classes:
1154 
1155 .. code-block:: cpp
1156 
1157     struct Cat {};
1158     struct Dog {};
1159 
1160     template <typename PetType>
1161     struct Cage {
1162         Cage(PetType& pet);
1163         PetType& get();
1164     };
1165 
1166 C++ templates may only be instantiated at compile time, so pybind11 can only
1167 wrap instantiated templated classes. You cannot wrap a non-instantiated template:
1168 
1169 .. code-block:: cpp
1170 
1171     // BROKEN (this will not compile)
1172     py::class_<Cage>(m, "Cage");
1173         .def("get", &Cage::get);
1174 
1175 You must explicitly specify each template/type combination that you want to
1176 wrap separately.
1177 
1178 .. code-block:: cpp
1179 
1180     // ok
1181     py::class_<Cage<Cat>>(m, "CatCage")
1182         .def("get", &Cage<Cat>::get);
1183 
1184     // ok
1185     py::class_<Cage<Dog>>(m, "DogCage")
1186         .def("get", &Cage<Dog>::get);
1187 
1188 If your class methods have template parameters you can wrap those as well,
1189 but once again each instantiation must be explicitly specified:
1190 
1191 .. code-block:: cpp
1192 
1193     typename <typename T>
1194     struct MyClass {
1195         template <typename V>
1196         T fn(V v);
1197     };
1198 
1199     py::class<MyClass<int>>(m, "MyClassT")
1200         .def("fn", &MyClass<int>::fn<std::string>);
1201 
1202 Custom automatic downcasters
1203 ============================
1204 
1205 As explained in :ref:`inheritance`, pybind11 comes with built-in
1206 understanding of the dynamic type of polymorphic objects in C++; that
1207 is, returning a Pet to Python produces a Python object that knows it's
1208 wrapping a Dog, if Pet has virtual methods and pybind11 knows about
1209 Dog and this Pet is in fact a Dog. Sometimes, you might want to
1210 provide this automatic downcasting behavior when creating bindings for
1211 a class hierarchy that does not use standard C++ polymorphism, such as
1212 LLVM [#f4]_. As long as there's some way to determine at runtime
1213 whether a downcast is safe, you can proceed by specializing the
1214 ``pybind11::polymorphic_type_hook`` template:
1215 
1216 .. code-block:: cpp
1217 
1218     enum class PetKind { Cat, Dog, Zebra };
1219     struct Pet {   // Not polymorphic: has no virtual methods
1220         const PetKind kind;
1221         int age = 0;
1222       protected:
1223         Pet(PetKind _kind) : kind(_kind) {}
1224     };
1225     struct Dog : Pet {
1226         Dog() : Pet(PetKind::Dog) {}
1227         std::string sound = "woof!";
1228         std::string bark() const { return sound; }
1229     };
1230 
1231     namespace PYBIND11_NAMESPACE {
1232         template<> struct polymorphic_type_hook<Pet> {
1233             static const void *get(const Pet *src, const std::type_info*& type) {
1234                 // note that src may be nullptr
1235                 if (src && src->kind == PetKind::Dog) {
1236                     type = &typeid(Dog);
1237                     return static_cast<const Dog*>(src);
1238                 }
1239                 return src;
1240             }
1241         };
1242     } // namespace PYBIND11_NAMESPACE
1243 
1244 When pybind11 wants to convert a C++ pointer of type ``Base*`` to a
1245 Python object, it calls ``polymorphic_type_hook<Base>::get()`` to
1246 determine if a downcast is possible. The ``get()`` function should use
1247 whatever runtime information is available to determine if its ``src``
1248 parameter is in fact an instance of some class ``Derived`` that
1249 inherits from ``Base``. If it finds such a ``Derived``, it sets ``type
1250 = &typeid(Derived)`` and returns a pointer to the ``Derived`` object
1251 that contains ``src``. Otherwise, it just returns ``src``, leaving
1252 ``type`` at its default value of nullptr. If you set ``type`` to a
1253 type that pybind11 doesn't know about, no downcasting will occur, and
1254 the original ``src`` pointer will be used with its static type
1255 ``Base*``.
1256 
1257 It is critical that the returned pointer and ``type`` argument of
1258 ``get()`` agree with each other: if ``type`` is set to something
1259 non-null, the returned pointer must point to the start of an object
1260 whose type is ``type``. If the hierarchy being exposed uses only
1261 single inheritance, a simple ``return src;`` will achieve this just
1262 fine, but in the general case, you must cast ``src`` to the
1263 appropriate derived-class pointer (e.g. using
1264 ``static_cast<Derived>(src)``) before allowing it to be returned as a
1265 ``void*``.
1266 
1267 .. [#f4] https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html
1268 
1269 .. note::
1270 
1271     pybind11's standard support for downcasting objects whose types
1272     have virtual methods is implemented using
1273     ``polymorphic_type_hook`` too, using the standard C++ ability to
1274     determine the most-derived type of a polymorphic object using
1275     ``typeid()`` and to cast a base pointer to that most-derived type
1276     (even if you don't know what it is) using ``dynamic_cast<void*>``.
1277 
1278 .. seealso::
1279 
1280     The file :file:`tests/test_tagbased_polymorphic.cpp` contains a
1281     more complete example, including a demonstration of how to provide
1282     automatic downcasting for an entire class hierarchy without
1283     writing one get() function for each class.
1284 
1285 Accessing the type object
1286 =========================
1287 
1288 You can get the type object from a C++ class that has already been registered using:
1289 
1290 .. code-block:: cpp
1291 
1292     py::type T_py = py::type::of<T>();
1293 
1294 You can directly use ``py::type::of(ob)`` to get the type object from any python
1295 object, just like ``type(ob)`` in Python.
1296 
1297 .. note::
1298 
1299     Other types, like ``py::type::of<int>()``, do not work, see :ref:`type-conversions`.
1300 
1301 .. versionadded:: 2.6
1302 
1303 Custom type setup
1304 =================
1305 
1306 For advanced use cases, such as enabling garbage collection support, you may
1307 wish to directly manipulate the ``PyHeapTypeObject`` corresponding to a
1308 ``py::class_`` definition.
1309 
1310 You can do that using ``py::custom_type_setup``:
1311 
1312 .. code-block:: cpp
1313 
1314    struct OwnsPythonObjects {
1315        py::object value = py::none();
1316    };
1317    py::class_<OwnsPythonObjects> cls(
1318        m, "OwnsPythonObjects", py::custom_type_setup([](PyHeapTypeObject *heap_type) {
1319            auto *type = &heap_type->ht_type;
1320            type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1321            type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) {
1322                auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
1323                Py_VISIT(self.value.ptr());
1324                return 0;
1325            };
1326            type->tp_clear = [](PyObject *self_base) {
1327                auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
1328                self.value = py::none();
1329                return 0;
1330            };
1331        }));
1332    cls.def(py::init<>());
1333    cls.def_readwrite("value", &OwnsPythonObjects::value);
1334 
1335 .. versionadded:: 2.8