2016-10-16 17:12:43 +00:00
|
|
|
Classes
|
|
|
|
#######
|
|
|
|
|
|
|
|
This section presents advanced binding code for classes and it is assumed
|
|
|
|
that you are already familiar with the basics from :doc:`/classes`.
|
|
|
|
|
|
|
|
.. _overriding_virtuals:
|
|
|
|
|
|
|
|
Overriding virtual functions in Python
|
|
|
|
======================================
|
|
|
|
|
2022-01-26 06:32:33 +00:00
|
|
|
Suppose that a C++ class or interface has a virtual function that we'd like
|
2016-10-16 17:12:43 +00:00
|
|
|
to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is
|
|
|
|
given as a specific example of how one would do this with traditional C++
|
|
|
|
code).
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class Animal {
|
|
|
|
public:
|
|
|
|
virtual ~Animal() { }
|
|
|
|
virtual std::string go(int n_times) = 0;
|
|
|
|
};
|
|
|
|
|
|
|
|
class Dog : public Animal {
|
|
|
|
public:
|
|
|
|
std::string go(int n_times) override {
|
|
|
|
std::string result;
|
|
|
|
for (int i=0; i<n_times; ++i)
|
|
|
|
result += "woof! ";
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Let's also suppose that we are given a plain function which calls the
|
|
|
|
function ``go()`` on an arbitrary ``Animal`` instance.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
std::string call_go(Animal *animal) {
|
|
|
|
return animal->go(3);
|
|
|
|
}
|
|
|
|
|
|
|
|
Normally, the binding code for these classes would look as follows:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
2017-04-23 23:51:44 +00:00
|
|
|
PYBIND11_MODULE(example, m) {
|
2018-05-07 13:18:08 +00:00
|
|
|
py::class_<Animal>(m, "Animal")
|
2016-10-16 17:12:43 +00:00
|
|
|
.def("go", &Animal::go);
|
|
|
|
|
2018-05-04 15:04:45 +00:00
|
|
|
py::class_<Dog, Animal>(m, "Dog")
|
2016-10-16 17:12:43 +00:00
|
|
|
.def(py::init<>());
|
|
|
|
|
|
|
|
m.def("call_go", &call_go);
|
|
|
|
}
|
|
|
|
|
|
|
|
However, these bindings are impossible to extend: ``Animal`` is not
|
|
|
|
constructible, and we clearly require some kind of "trampoline" that
|
|
|
|
redirects virtual calls back to Python.
|
|
|
|
|
|
|
|
Defining a new type of ``Animal`` from within Python is possible but requires a
|
|
|
|
helper class that is defined as follows:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class PyAnimal : public Animal {
|
|
|
|
public:
|
|
|
|
/* Inherit the constructors */
|
|
|
|
using Animal::Animal;
|
|
|
|
|
|
|
|
/* Trampoline (need one for each virtual function) */
|
|
|
|
std::string go(int n_times) override {
|
2020-09-15 12:56:20 +00:00
|
|
|
PYBIND11_OVERRIDE_PURE(
|
2016-10-16 17:12:43 +00:00
|
|
|
std::string, /* Return type */
|
|
|
|
Animal, /* Parent class */
|
2017-01-13 10:17:29 +00:00
|
|
|
go, /* Name of function in C++ (must match Python name) */
|
2016-10-16 17:12:43 +00:00
|
|
|
n_times /* Argument(s) */
|
|
|
|
);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-09-15 12:56:20 +00:00
|
|
|
The macro :c:macro:`PYBIND11_OVERRIDE_PURE` should be used for pure virtual
|
|
|
|
functions, and :c:macro:`PYBIND11_OVERRIDE` should be used for functions which have
|
2020-07-20 17:35:21 +00:00
|
|
|
a default implementation. There are also two alternate macros
|
2020-09-15 12:56:20 +00:00
|
|
|
:c:macro:`PYBIND11_OVERRIDE_PURE_NAME` and :c:macro:`PYBIND11_OVERRIDE_NAME` which
|
2016-10-16 17:12:43 +00:00
|
|
|
take a string-valued name argument between the *Parent class* and *Name of the
|
2017-08-17 15:03:46 +00:00
|
|
|
function* slots, which defines the name of function in Python. This is required
|
2017-01-13 10:17:29 +00:00
|
|
|
when the C++ and Python versions of the
|
2016-10-16 17:12:43 +00:00
|
|
|
function have different names, e.g. ``operator()`` vs ``__call__``.
|
|
|
|
|
|
|
|
The binding code also needs a few minor adaptations (highlighted):
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
2018-05-04 15:04:45 +00:00
|
|
|
:emphasize-lines: 2,3
|
2016-10-16 17:12:43 +00:00
|
|
|
|
2017-04-23 23:51:44 +00:00
|
|
|
PYBIND11_MODULE(example, m) {
|
2018-05-07 13:18:08 +00:00
|
|
|
py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal")
|
2016-10-16 17:12:43 +00:00
|
|
|
.def(py::init<>())
|
|
|
|
.def("go", &Animal::go);
|
|
|
|
|
2018-05-04 15:04:45 +00:00
|
|
|
py::class_<Dog, Animal>(m, "Dog")
|
2016-10-16 17:12:43 +00:00
|
|
|
.def(py::init<>());
|
|
|
|
|
|
|
|
m.def("call_go", &call_go);
|
|
|
|
}
|
|
|
|
|
|
|
|
Importantly, pybind11 is made aware of the trampoline helper class by
|
2017-01-13 10:17:29 +00:00
|
|
|
specifying it as an extra template argument to :class:`class_`. (This can also
|
2016-10-16 17:12:43 +00:00
|
|
|
be combined with other template arguments such as a custom holder type; the
|
|
|
|
order of template types does not matter). Following this, we are able to
|
|
|
|
define a constructor as usual.
|
|
|
|
|
2017-01-13 10:17:29 +00:00
|
|
|
Bindings should be made against the actual class, not the trampoline helper class.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
2018-05-04 15:04:45 +00:00
|
|
|
:emphasize-lines: 3
|
2017-01-13 10:17:29 +00:00
|
|
|
|
2018-05-04 15:04:45 +00:00
|
|
|
py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal");
|
|
|
|
.def(py::init<>())
|
|
|
|
.def("go", &PyAnimal::go); /* <--- THIS IS WRONG, use &Animal::go */
|
2017-01-13 10:17:29 +00:00
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
Note, however, that the above is sufficient for allowing python classes to
|
2017-08-07 22:37:42 +00:00
|
|
|
extend ``Animal``, but not ``Dog``: see :ref:`virtual_and_inheritance` for the
|
2020-09-15 12:56:20 +00:00
|
|
|
necessary steps required to providing proper overriding support for inherited
|
2016-10-16 17:12:43 +00:00
|
|
|
classes.
|
|
|
|
|
|
|
|
The Python session below shows how to override ``Animal::go`` and invoke it via
|
|
|
|
a virtual method call.
|
|
|
|
|
|
|
|
.. code-block:: pycon
|
|
|
|
|
|
|
|
>>> from example import *
|
|
|
|
>>> d = Dog()
|
|
|
|
>>> call_go(d)
|
2022-02-11 02:28:08 +00:00
|
|
|
'woof! woof! woof! '
|
2016-10-16 17:12:43 +00:00
|
|
|
>>> class Cat(Animal):
|
|
|
|
... def go(self, n_times):
|
2021-09-22 19:38:50 +00:00
|
|
|
... return "meow! " * n_times
|
2016-10-16 17:12:43 +00:00
|
|
|
...
|
|
|
|
>>> c = Cat()
|
|
|
|
>>> call_go(c)
|
2022-02-11 02:28:08 +00:00
|
|
|
'meow! meow! meow! '
|
2016-10-16 17:12:43 +00:00
|
|
|
|
2017-08-07 22:37:42 +00:00
|
|
|
If you are defining a custom constructor in a derived Python class, you *must*
|
|
|
|
ensure that you explicitly call the bound C++ constructor using ``__init__``,
|
|
|
|
*regardless* of whether it is a default constructor or not. Otherwise, the
|
|
|
|
memory for the C++ portion of the instance will be left uninitialized, which
|
|
|
|
will generally leave the C++ instance in an invalid state and cause undefined
|
|
|
|
behavior if the C++ instance is subsequently used.
|
|
|
|
|
2020-08-19 18:53:59 +00:00
|
|
|
.. versionchanged:: 2.6
|
2020-07-07 10:04:06 +00:00
|
|
|
The default pybind11 metaclass will throw a ``TypeError`` when it detects
|
|
|
|
that ``__init__`` was not called by a derived class.
|
|
|
|
|
2017-08-07 22:37:42 +00:00
|
|
|
Here is an example:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
2019-06-10 20:02:58 +00:00
|
|
|
class Dachshund(Dog):
|
2017-08-07 22:37:42 +00:00
|
|
|
def __init__(self, name):
|
2021-09-22 19:38:50 +00:00
|
|
|
Dog.__init__(self) # Without this, a TypeError is raised.
|
2017-08-07 22:37:42 +00:00
|
|
|
self.name = name
|
2021-09-22 19:38:50 +00:00
|
|
|
|
2017-08-07 22:37:42 +00:00
|
|
|
def bark(self):
|
|
|
|
return "yap!"
|
|
|
|
|
|
|
|
Note that a direct ``__init__`` constructor *should be called*, and ``super()``
|
|
|
|
should not be used. For simple cases of linear inheritance, ``super()``
|
|
|
|
may work, but once you begin mixing Python and C++ multiple inheritance,
|
|
|
|
things will fall apart due to differences between Python's MRO and C++'s
|
|
|
|
mechanisms.
|
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
Please take a look at the :ref:`macro_notes` before using this feature.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
When the overridden type returns a reference or pointer to a type that
|
|
|
|
pybind11 converts from Python (for example, numeric values, std::string,
|
|
|
|
and other built-in value-converting types), there are some limitations to
|
|
|
|
be aware of:
|
|
|
|
|
|
|
|
- because in these cases there is no C++ variable to reference (the value
|
|
|
|
is stored in the referenced Python variable), pybind11 provides one in
|
2020-09-15 12:56:20 +00:00
|
|
|
the PYBIND11_OVERRIDE macros (when needed) with static storage duration.
|
|
|
|
Note that this means that invoking the overridden method on *any*
|
2016-10-16 17:12:43 +00:00
|
|
|
instance will change the referenced value stored in *all* instances of
|
|
|
|
that type.
|
|
|
|
|
|
|
|
- Attempts to modify a non-const reference will not have the desired
|
|
|
|
effect: it will change only the static cache variable, but this change
|
|
|
|
will not propagate to underlying Python instance, and the change will be
|
2020-09-15 12:56:20 +00:00
|
|
|
replaced the next time the override is invoked.
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
The :c:macro:`PYBIND11_OVERRIDE` and accompanying macros used to be called
|
|
|
|
``PYBIND11_OVERLOAD`` up until pybind11 v2.5.0, and :func:`get_override`
|
|
|
|
used to be called ``get_overload``. This naming was corrected and the older
|
2020-09-15 16:10:31 +00:00
|
|
|
macro and function names may soon be deprecated, in order to reduce
|
|
|
|
confusion with overloaded functions and methods and ``py::overload_cast``
|
|
|
|
(see :ref:`classes`).
|
2016-10-16 17:12:43 +00:00
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
The file :file:`tests/test_virtual_functions.cpp` contains a complete
|
|
|
|
example that demonstrates how to override virtual functions using pybind11
|
|
|
|
in more detail.
|
|
|
|
|
|
|
|
.. _virtual_and_inheritance:
|
|
|
|
|
|
|
|
Combining virtual functions and inheritance
|
|
|
|
===========================================
|
|
|
|
|
|
|
|
When combining virtual methods with inheritance, you need to be sure to provide
|
|
|
|
an override for each method for which you want to allow overrides from derived
|
|
|
|
python classes. For example, suppose we extend the above ``Animal``/``Dog``
|
|
|
|
example as follows:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class Animal {
|
|
|
|
public:
|
|
|
|
virtual std::string go(int n_times) = 0;
|
|
|
|
virtual std::string name() { return "unknown"; }
|
|
|
|
};
|
2017-01-13 10:15:52 +00:00
|
|
|
class Dog : public Animal {
|
2016-10-16 17:12:43 +00:00
|
|
|
public:
|
|
|
|
std::string go(int n_times) override {
|
|
|
|
std::string result;
|
|
|
|
for (int i=0; i<n_times; ++i)
|
|
|
|
result += bark() + " ";
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
virtual std::string bark() { return "woof!"; }
|
|
|
|
};
|
|
|
|
|
|
|
|
then the trampoline class for ``Animal`` must, as described in the previous
|
|
|
|
section, override ``go()`` and ``name()``, but in order to allow python code to
|
|
|
|
inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that
|
|
|
|
overrides both the added ``bark()`` method *and* the ``go()`` and ``name()``
|
|
|
|
methods inherited from ``Animal`` (even though ``Dog`` doesn't directly
|
|
|
|
override the ``name()`` method):
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class PyAnimal : public Animal {
|
|
|
|
public:
|
|
|
|
using Animal::Animal; // Inherit constructors
|
2020-09-15 12:56:20 +00:00
|
|
|
std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Animal, go, n_times); }
|
|
|
|
std::string name() override { PYBIND11_OVERRIDE(std::string, Animal, name, ); }
|
2016-10-16 17:12:43 +00:00
|
|
|
};
|
|
|
|
class PyDog : public Dog {
|
|
|
|
public:
|
|
|
|
using Dog::Dog; // Inherit constructors
|
2020-09-15 12:56:20 +00:00
|
|
|
std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, Dog, go, n_times); }
|
|
|
|
std::string name() override { PYBIND11_OVERRIDE(std::string, Dog, name, ); }
|
|
|
|
std::string bark() override { PYBIND11_OVERRIDE(std::string, Dog, bark, ); }
|
2016-10-16 17:12:43 +00:00
|
|
|
};
|
|
|
|
|
2017-03-22 20:39:19 +00:00
|
|
|
.. note::
|
|
|
|
|
2021-04-02 15:46:43 +00:00
|
|
|
Note the trailing commas in the ``PYBIND11_OVERRIDE`` calls to ``name()``
|
2017-03-22 20:39:19 +00:00
|
|
|
and ``bark()``. These are needed to portably implement a trampoline for a
|
|
|
|
function that does not take any arguments. For functions that take
|
|
|
|
a nonzero number of arguments, the trailing comma must be omitted.
|
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
A registered class derived from a pybind11-registered class with virtual
|
|
|
|
methods requires a similar trampoline class, *even if* it doesn't explicitly
|
|
|
|
declare or override any virtual methods itself:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class Husky : public Dog {};
|
|
|
|
class PyHusky : public Husky {
|
2017-01-13 10:15:52 +00:00
|
|
|
public:
|
|
|
|
using Husky::Husky; // Inherit constructors
|
2020-09-15 12:56:20 +00:00
|
|
|
std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Husky, go, n_times); }
|
|
|
|
std::string name() override { PYBIND11_OVERRIDE(std::string, Husky, name, ); }
|
|
|
|
std::string bark() override { PYBIND11_OVERRIDE(std::string, Husky, bark, ); }
|
2016-10-16 17:12:43 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
There is, however, a technique that can be used to avoid this duplication
|
|
|
|
(which can be especially helpful for a base class with several virtual
|
|
|
|
methods). The technique involves using template trampoline classes, as
|
|
|
|
follows:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
template <class AnimalBase = Animal> class PyAnimal : public AnimalBase {
|
2017-01-13 10:15:52 +00:00
|
|
|
public:
|
2016-10-16 17:12:43 +00:00
|
|
|
using AnimalBase::AnimalBase; // Inherit constructors
|
2020-09-15 12:56:20 +00:00
|
|
|
std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, AnimalBase, go, n_times); }
|
|
|
|
std::string name() override { PYBIND11_OVERRIDE(std::string, AnimalBase, name, ); }
|
2016-10-16 17:12:43 +00:00
|
|
|
};
|
|
|
|
template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> {
|
2017-01-13 10:15:52 +00:00
|
|
|
public:
|
2016-10-16 17:12:43 +00:00
|
|
|
using PyAnimal<DogBase>::PyAnimal; // Inherit constructors
|
|
|
|
// Override PyAnimal's pure virtual go() with a non-pure one:
|
2020-09-15 12:56:20 +00:00
|
|
|
std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, DogBase, go, n_times); }
|
|
|
|
std::string bark() override { PYBIND11_OVERRIDE(std::string, DogBase, bark, ); }
|
2016-10-16 17:12:43 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
This technique has the advantage of requiring just one trampoline method to be
|
|
|
|
declared per virtual method and pure virtual method override. It does,
|
|
|
|
however, require the compiler to generate at least as many methods (and
|
|
|
|
possibly more, if both pure virtual and overridden pure virtual methods are
|
|
|
|
exposed, as above).
|
|
|
|
|
|
|
|
The classes are then registered with pybind11 using:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
py::class_<Animal, PyAnimal<>> animal(m, "Animal");
|
2020-06-30 22:25:17 +00:00
|
|
|
py::class_<Dog, Animal, PyDog<>> dog(m, "Dog");
|
|
|
|
py::class_<Husky, Dog, PyDog<Husky>> husky(m, "Husky");
|
2016-10-16 17:12:43 +00:00
|
|
|
// ... add animal, dog, husky definitions
|
|
|
|
|
|
|
|
Note that ``Husky`` did not require a dedicated trampoline template class at
|
|
|
|
all, since it neither declares any new virtual methods nor provides any pure
|
|
|
|
virtual method implementations.
|
|
|
|
|
|
|
|
With either the repeated-virtuals or templated trampoline methods in place, you
|
|
|
|
can now create a python class that inherits from ``Dog``:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
class ShihTzu(Dog):
|
|
|
|
def bark(self):
|
|
|
|
return "yip!"
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
See the file :file:`tests/test_virtual_functions.cpp` for complete examples
|
|
|
|
using both the duplication and templated trampoline approaches.
|
|
|
|
|
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
|
|
|
.. _extended_aliases:
|
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
Extended trampoline class functionality
|
|
|
|
=======================================
|
|
|
|
|
2019-06-11 08:57:49 +00:00
|
|
|
.. _extended_class_functionality_forced_trampoline:
|
2019-06-10 20:12:28 +00:00
|
|
|
|
|
|
|
Forced trampoline class initialisation
|
|
|
|
--------------------------------------
|
2016-10-16 17:12:43 +00:00
|
|
|
The trampoline classes described in the previous sections are, by default, only
|
|
|
|
initialized when needed. More specifically, they are initialized when a python
|
|
|
|
class actually inherits from a registered type (instead of merely creating an
|
|
|
|
instance of the registered type), or when a registered constructor is only
|
|
|
|
valid for the trampoline class but not the registered class. This is primarily
|
|
|
|
for performance reasons: when the trampoline class is not needed for anything
|
|
|
|
except virtual method dispatching, not initializing the trampoline class
|
|
|
|
improves performance by avoiding needing to do a run-time check to see if the
|
2020-09-15 12:56:20 +00:00
|
|
|
inheriting python instance has an overridden method.
|
2016-10-16 17:12:43 +00:00
|
|
|
|
|
|
|
Sometimes, however, it is useful to always initialize a trampoline class as an
|
|
|
|
intermediate class that does more than just handle virtual method dispatching.
|
|
|
|
For example, such a class might perform extra class initialization, extra
|
|
|
|
destruction operations, and might define new members and methods to enable a
|
|
|
|
more python-like interface to a class.
|
|
|
|
|
|
|
|
In order to tell pybind11 that it should *always* initialize the trampoline
|
|
|
|
class when creating new instances of a type, the class constructors should be
|
|
|
|
declared using ``py::init_alias<Args, ...>()`` instead of the usual
|
|
|
|
``py::init<Args, ...>()``. This forces construction via the trampoline class,
|
|
|
|
ensuring member initialization and (eventual) destruction.
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
2017-06-22 21:42:11 +00:00
|
|
|
See the file :file:`tests/test_virtual_functions.cpp` for complete examples
|
2016-10-16 17:12:43 +00:00
|
|
|
showing both normal and forced trampoline instantiation.
|
|
|
|
|
2019-06-10 20:12:28 +00:00
|
|
|
Different method signatures
|
|
|
|
---------------------------
|
|
|
|
The macro's introduced in :ref:`overriding_virtuals` cover most of the standard
|
|
|
|
use cases when exposing C++ classes to Python. Sometimes it is hard or unwieldy
|
|
|
|
to create a direct one-on-one mapping between the arguments and method return
|
|
|
|
type.
|
|
|
|
|
|
|
|
An example would be when the C++ signature contains output arguments using
|
|
|
|
references (See also :ref:`faq_reference_arguments`). Another way of solving
|
|
|
|
this is to use the method body of the trampoline class to do conversions to the
|
|
|
|
input and return of the Python method.
|
|
|
|
|
2020-09-15 12:56:20 +00:00
|
|
|
The main building block to do so is the :func:`get_override`, this function
|
2019-06-10 20:12:28 +00:00
|
|
|
allows retrieving a method implemented in Python from within the trampoline's
|
|
|
|
methods. Consider for example a C++ method which has the signature
|
|
|
|
``bool myMethod(int32_t& value)``, where the return indicates whether
|
|
|
|
something should be done with the ``value``. This can be made convenient on the
|
|
|
|
Python side by allowing the Python function to return ``None`` or an ``int``:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
bool MyClass::myMethod(int32_t& value)
|
|
|
|
{
|
|
|
|
pybind11::gil_scoped_acquire gil; // Acquire the GIL while in this scope.
|
2020-09-15 12:56:20 +00:00
|
|
|
// Try to look up the overridden method on the Python side.
|
|
|
|
pybind11::function override = pybind11::get_override(this, "myMethod");
|
|
|
|
if (override) { // method is found
|
|
|
|
auto obj = override(value); // Call the Python function.
|
2019-06-10 20:12:28 +00:00
|
|
|
if (py::isinstance<py::int_>(obj)) { // check if it returned a Python integer type
|
|
|
|
value = obj.cast<int32_t>(); // Cast it and assign it to the value.
|
|
|
|
return true; // Return true; value should be used.
|
|
|
|
} else {
|
|
|
|
return false; // Python returned none, return false.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false; // Alternatively return MyClass::myMethod(value);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
.. _custom_constructors:
|
|
|
|
|
|
|
|
Custom constructors
|
|
|
|
===================
|
|
|
|
|
|
|
|
The syntax for binding constructors was previously introduced, but it only
|
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
|
|
|
works when a constructor of the appropriate arguments actually exists on the
|
2017-09-05 14:49:33 +00:00
|
|
|
C++ side. To extend this to more general cases, pybind11 makes it possible
|
|
|
|
to bind factory functions as constructors. For example, suppose you have a
|
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
|
|
|
class like this:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class Example {
|
|
|
|
private:
|
|
|
|
Example(int); // private constructor
|
|
|
|
public:
|
|
|
|
// Factory function:
|
|
|
|
static Example create(int a) { return Example(a); }
|
|
|
|
};
|
|
|
|
|
2017-09-05 14:49:33 +00:00
|
|
|
py::class_<Example>(m, "Example")
|
|
|
|
.def(py::init(&Example::create));
|
|
|
|
|
2017-08-21 22:55:53 +00:00
|
|
|
While it is possible to create a straightforward binding of the static
|
|
|
|
``create`` method, it may sometimes be preferable to expose it as a constructor
|
|
|
|
on the Python side. This can be accomplished by calling ``.def(py::init(...))``
|
|
|
|
with the function reference returning the new instance passed as an argument.
|
|
|
|
It is also possible to use this approach to bind a function returning a new
|
|
|
|
instance by raw pointer or by the holder (e.g. ``std::unique_ptr``).
|
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
|
|
|
|
|
|
|
The following example shows the different approaches:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class Example {
|
|
|
|
private:
|
|
|
|
Example(int); // private constructor
|
|
|
|
public:
|
|
|
|
// Factory function - returned by value:
|
|
|
|
static Example create(int a) { return Example(a); }
|
|
|
|
|
|
|
|
// These constructors are publicly callable:
|
|
|
|
Example(double);
|
|
|
|
Example(int, int);
|
|
|
|
Example(std::string);
|
|
|
|
};
|
|
|
|
|
|
|
|
py::class_<Example>(m, "Example")
|
|
|
|
// Bind the factory function as a constructor:
|
|
|
|
.def(py::init(&Example::create))
|
|
|
|
// Bind a lambda function returning a pointer wrapped in a holder:
|
|
|
|
.def(py::init([](std::string arg) {
|
|
|
|
return std::unique_ptr<Example>(new Example(arg));
|
|
|
|
}))
|
|
|
|
// Return a raw pointer:
|
|
|
|
.def(py::init([](int a, int b) { return new Example(a, b); }))
|
|
|
|
// You can mix the above with regular C++ constructor bindings as well:
|
|
|
|
.def(py::init<double>())
|
|
|
|
;
|
|
|
|
|
|
|
|
When the constructor is invoked from Python, pybind11 will call the factory
|
|
|
|
function and store the resulting C++ instance in the Python instance.
|
|
|
|
|
2017-08-21 22:55:53 +00:00
|
|
|
When combining factory functions constructors with :ref:`virtual function
|
|
|
|
trampolines <overriding_virtuals>` there are two approaches. The first is to
|
|
|
|
add a constructor to the alias class that takes a base value by
|
|
|
|
rvalue-reference. If such a constructor is available, it will be used to
|
|
|
|
construct an alias instance from the value returned by the factory function.
|
|
|
|
The second option is to provide two factory functions to ``py::init()``: the
|
|
|
|
first will be invoked when no alias class is required (i.e. when the class is
|
|
|
|
being used but not inherited from in Python), and the second will be invoked
|
|
|
|
when an alias is required.
|
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
|
|
|
|
|
|
|
You can also specify a single factory function that always returns an alias
|
|
|
|
instance: this will result in behaviour similar to ``py::init_alias<...>()``,
|
2017-08-21 22:55:53 +00:00
|
|
|
as described in the :ref:`extended trampoline class documentation
|
|
|
|
<extended_aliases>`.
|
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
|
|
|
|
|
|
|
The following example shows the different factory approaches for a class with
|
|
|
|
an alias:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
#include <pybind11/factory.h>
|
|
|
|
class Example {
|
|
|
|
public:
|
|
|
|
// ...
|
|
|
|
virtual ~Example() = default;
|
|
|
|
};
|
|
|
|
class PyExample : public Example {
|
|
|
|
public:
|
|
|
|
using Example::Example;
|
|
|
|
PyExample(Example &&base) : Example(std::move(base)) {}
|
|
|
|
};
|
|
|
|
py::class_<Example, PyExample>(m, "Example")
|
|
|
|
// Returns an Example pointer. If a PyExample is needed, the Example
|
|
|
|
// instance will be moved via the extra constructor in PyExample, above.
|
|
|
|
.def(py::init([]() { return new Example(); }))
|
|
|
|
// Two callbacks:
|
|
|
|
.def(py::init([]() { return new Example(); } /* no alias needed */,
|
|
|
|
[]() { return new PyExample(); } /* alias needed */))
|
|
|
|
// *Always* returns an alias instance (like py::init_alias<>())
|
|
|
|
.def(py::init([]() { return new PyExample(); }))
|
|
|
|
;
|
|
|
|
|
2017-08-21 20:48:28 +00:00
|
|
|
Brace initialization
|
|
|
|
--------------------
|
|
|
|
|
|
|
|
``pybind11::init<>`` internally uses C++11 brace initialization to call the
|
|
|
|
constructor of the target class. This means that it can be used to bind
|
|
|
|
*implicit* constructors as well:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
struct Aggregate {
|
|
|
|
int a;
|
|
|
|
std::string b;
|
|
|
|
};
|
|
|
|
|
|
|
|
py::class_<Aggregate>(m, "Aggregate")
|
|
|
|
.def(py::init<int, const std::string &>());
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
Note that brace initialization preferentially invokes constructor overloads
|
|
|
|
taking a ``std::initializer_list``. In the rare event that this causes an
|
|
|
|
issue, you can work around it by using ``py::init(...)`` with a lambda
|
|
|
|
function that constructs the new object as desired.
|
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
.. _classes_with_non_public_destructors:
|
|
|
|
|
|
|
|
Non-public destructors
|
|
|
|
======================
|
|
|
|
|
|
|
|
If a class has a private or protected destructor (as might e.g. be the case in
|
|
|
|
a singleton pattern), a compile error will occur when creating bindings via
|
|
|
|
pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that
|
|
|
|
is responsible for managing the lifetime of instances will reference the
|
|
|
|
destructor even if no deallocations ever take place. In order to expose classes
|
|
|
|
with private or protected destructors, it is possible to override the holder
|
|
|
|
type via a holder type argument to ``class_``. Pybind11 provides a helper class
|
|
|
|
``py::nodelete`` that disables any destructor invocations. In this case, it is
|
|
|
|
crucial that instances are deallocated on the C++ side to avoid memory leaks.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
/* ... definition ... */
|
|
|
|
|
|
|
|
class MyClass {
|
|
|
|
private:
|
|
|
|
~MyClass() { }
|
|
|
|
};
|
|
|
|
|
|
|
|
/* ... binding code ... */
|
|
|
|
|
|
|
|
py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass")
|
2017-01-13 10:15:52 +00:00
|
|
|
.def(py::init<>())
|
2016-10-16 17:12:43 +00:00
|
|
|
|
2020-08-08 10:07:14 +00:00
|
|
|
.. _destructors_that_call_python:
|
|
|
|
|
|
|
|
Destructors that call Python
|
|
|
|
============================
|
|
|
|
|
|
|
|
If a Python function is invoked from a C++ destructor, an exception may be thrown
|
|
|
|
of type :class:`error_already_set`. If this error is thrown out of a class destructor,
|
|
|
|
``std::terminate()`` will be called, terminating the process. Class destructors
|
|
|
|
must catch all exceptions of type :class:`error_already_set` to discard the Python
|
|
|
|
exception using :func:`error_already_set::discard_as_unraisable`.
|
|
|
|
|
|
|
|
Every Python function should be treated as *possibly throwing*. When a Python generator
|
|
|
|
stops yielding items, Python will throw a ``StopIteration`` exception, which can pass
|
|
|
|
though C++ destructors if the generator's stack frame holds the last reference to C++
|
|
|
|
objects.
|
|
|
|
|
|
|
|
For more information, see :ref:`the documentation on exceptions <unraisable_exceptions>`.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class MyClass {
|
|
|
|
public:
|
|
|
|
~MyClass() {
|
|
|
|
try {
|
|
|
|
py::print("Even printing is dangerous in a destructor");
|
|
|
|
py::exec("raise ValueError('This is an unraisable exception')");
|
|
|
|
} catch (py::error_already_set &e) {
|
|
|
|
// error_context should be information about where/why the occurred,
|
|
|
|
// e.g. use __func__ to get the name of the current function
|
|
|
|
e.discard_as_unraisable(__func__);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
pybind11 does not support C++ destructors marked ``noexcept(false)``.
|
|
|
|
|
2020-08-19 18:53:59 +00:00
|
|
|
.. versionadded:: 2.6
|
|
|
|
|
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
|
|
|
.. _implicit_conversions:
|
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
Implicit conversions
|
|
|
|
====================
|
|
|
|
|
|
|
|
Suppose that instances of two types ``A`` and ``B`` are used in a project, and
|
|
|
|
that an ``A`` can easily be converted into an instance of type ``B`` (examples of this
|
|
|
|
could be a fixed and an arbitrary precision number type).
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
py::class_<A>(m, "A")
|
|
|
|
/// ... members ...
|
|
|
|
|
|
|
|
py::class_<B>(m, "B")
|
|
|
|
.def(py::init<A>())
|
|
|
|
/// ... members ...
|
|
|
|
|
|
|
|
m.def("func",
|
|
|
|
[](const B &) { /* .... */ }
|
|
|
|
);
|
|
|
|
|
|
|
|
To invoke the function ``func`` using a variable ``a`` containing an ``A``
|
|
|
|
instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
|
|
|
|
will automatically apply an implicit type conversion, which makes it possible
|
|
|
|
to directly write ``func(a)``.
|
|
|
|
|
|
|
|
In this situation (i.e. where ``B`` has a constructor that converts from
|
|
|
|
``A``), the following statement enables similar implicit conversions on the
|
|
|
|
Python side:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
py::implicitly_convertible<A, B>();
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom
|
|
|
|
data type that is exposed to Python via pybind11.
|
|
|
|
|
2017-08-28 14:34:06 +00:00
|
|
|
To prevent runaway recursion, implicit conversions are non-reentrant: an
|
|
|
|
implicit conversion invoked as part of another implicit conversion of the
|
|
|
|
same type (i.e. from ``A`` to ``B``) will fail.
|
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
.. _static_properties:
|
|
|
|
|
|
|
|
Static properties
|
|
|
|
=================
|
|
|
|
|
|
|
|
The section on :ref:`properties` discussed the creation of instance properties
|
|
|
|
that are implemented in terms of C++ getters and setters.
|
|
|
|
|
|
|
|
Static properties can also be created in a similar way to expose getters and
|
2017-02-16 22:02:56 +00:00
|
|
|
setters of static class attributes. Note that the implicit ``self`` argument
|
|
|
|
also exists in this case and is used to pass the Python ``type`` subclass
|
|
|
|
instance. This parameter will often not be needed by the C++ side, and the
|
|
|
|
following example illustrates how to instantiate a lambda getter function
|
|
|
|
that ignores it:
|
2016-10-16 17:12:43 +00:00
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
2017-02-16 22:02:56 +00:00
|
|
|
py::class_<Foo>(m, "Foo")
|
2016-10-16 17:12:43 +00:00
|
|
|
.def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); });
|
|
|
|
|
|
|
|
Operator overloading
|
|
|
|
====================
|
|
|
|
|
|
|
|
Suppose that we're given the following ``Vector2`` class with a vector addition
|
|
|
|
and scalar multiplication operation, all implemented using overloaded operators
|
|
|
|
in C++.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class Vector2 {
|
|
|
|
public:
|
|
|
|
Vector2(float x, float y) : x(x), y(y) { }
|
|
|
|
|
|
|
|
Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
|
|
|
|
Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
|
|
|
|
Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
|
|
|
|
Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
|
|
|
|
|
|
|
|
friend Vector2 operator*(float f, const Vector2 &v) {
|
|
|
|
return Vector2(f * v.x, f * v.y);
|
|
|
|
}
|
|
|
|
|
|
|
|
std::string toString() const {
|
|
|
|
return "[" + std::to_string(x) + ", " + std::to_string(y) + "]";
|
|
|
|
}
|
|
|
|
private:
|
|
|
|
float x, y;
|
|
|
|
};
|
|
|
|
|
|
|
|
The following snippet shows how the above operators can be conveniently exposed
|
|
|
|
to Python.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
#include <pybind11/operators.h>
|
|
|
|
|
2017-04-23 23:51:44 +00:00
|
|
|
PYBIND11_MODULE(example, m) {
|
2016-10-16 17:12:43 +00:00
|
|
|
py::class_<Vector2>(m, "Vector2")
|
|
|
|
.def(py::init<float, float>())
|
|
|
|
.def(py::self + py::self)
|
|
|
|
.def(py::self += py::self)
|
|
|
|
.def(py::self *= float())
|
|
|
|
.def(float() * py::self)
|
2017-01-13 10:15:52 +00:00
|
|
|
.def(py::self * float())
|
2019-06-22 10:07:41 +00:00
|
|
|
.def(-py::self)
|
2016-10-16 17:12:43 +00:00
|
|
|
.def("__repr__", &Vector2::toString);
|
|
|
|
}
|
|
|
|
|
|
|
|
Note that a line like
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
.def(py::self * float())
|
|
|
|
|
|
|
|
is really just short hand notation for
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
.def("__mul__", [](const Vector2 &a, float b) {
|
|
|
|
return a * b;
|
|
|
|
}, py::is_operator())
|
|
|
|
|
|
|
|
This can be useful for exposing additional operators that don't exist on the
|
|
|
|
C++ side, or to perform other types of customization. The ``py::is_operator``
|
|
|
|
flag marker is needed to inform pybind11 that this is an operator, which
|
|
|
|
returns ``NotImplemented`` when invoked with incompatible arguments rather than
|
|
|
|
throwing a type error.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
To use the more convenient ``py::self`` notation, the additional
|
|
|
|
header file :file:`pybind11/operators.h` must be included.
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
The file :file:`tests/test_operator_overloading.cpp` contains a
|
|
|
|
complete example that demonstrates how to work with overloaded operators in
|
|
|
|
more detail.
|
|
|
|
|
2017-08-23 23:53:15 +00:00
|
|
|
.. _pickling:
|
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
Pickling support
|
|
|
|
================
|
|
|
|
|
|
|
|
Python's ``pickle`` module provides a powerful facility to serialize and
|
|
|
|
de-serialize a Python object graph into a binary data stream. To pickle and
|
2017-08-23 23:53:15 +00:00
|
|
|
unpickle C++ classes using pybind11, a ``py::pickle()`` definition must be
|
|
|
|
provided. Suppose the class in question has the following signature:
|
2016-10-16 17:12:43 +00:00
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class Pickleable {
|
|
|
|
public:
|
|
|
|
Pickleable(const std::string &value) : m_value(value) { }
|
|
|
|
const std::string &value() const { return m_value; }
|
|
|
|
|
|
|
|
void setExtra(int extra) { m_extra = extra; }
|
|
|
|
int extra() const { return m_extra; }
|
|
|
|
private:
|
|
|
|
std::string m_value;
|
|
|
|
int m_extra = 0;
|
|
|
|
};
|
|
|
|
|
2017-09-04 21:00:19 +00:00
|
|
|
Pickling support in Python is enabled by defining the ``__setstate__`` and
|
2017-08-23 23:53:15 +00:00
|
|
|
``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()``
|
|
|
|
to bind these two functions:
|
2016-10-16 17:12:43 +00:00
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
py::class_<Pickleable>(m, "Pickleable")
|
|
|
|
.def(py::init<std::string>())
|
|
|
|
.def("value", &Pickleable::value)
|
|
|
|
.def("extra", &Pickleable::extra)
|
|
|
|
.def("setExtra", &Pickleable::setExtra)
|
2017-08-23 23:53:15 +00:00
|
|
|
.def(py::pickle(
|
|
|
|
[](const Pickleable &p) { // __getstate__
|
|
|
|
/* Return a tuple that fully encodes the state of the object */
|
|
|
|
return py::make_tuple(p.value(), p.extra());
|
|
|
|
},
|
|
|
|
[](py::tuple t) { // __setstate__
|
|
|
|
if (t.size() != 2)
|
|
|
|
throw std::runtime_error("Invalid state!");
|
|
|
|
|
|
|
|
/* Create a new C++ instance */
|
|
|
|
Pickleable p(t[0].cast<std::string>());
|
|
|
|
|
|
|
|
/* Assign any additional state */
|
|
|
|
p.setExtra(t[1].cast<int>());
|
|
|
|
|
|
|
|
return p;
|
|
|
|
}
|
|
|
|
));
|
|
|
|
|
2021-07-10 18:16:07 +00:00
|
|
|
The ``__setstate__`` part of the ``py::pickle()`` definition follows the same
|
2017-08-23 23:53:15 +00:00
|
|
|
rules as the single-argument version of ``py::init()``. The return type can be
|
|
|
|
a value, pointer or holder type. See :ref:`custom_constructors` for details.
|
2016-10-16 17:12:43 +00:00
|
|
|
|
|
|
|
An instance can now be pickled as follows:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
2022-02-11 02:28:08 +00:00
|
|
|
import pickle
|
2016-10-16 17:12:43 +00:00
|
|
|
|
|
|
|
p = Pickleable("test_value")
|
|
|
|
p.setExtra(15)
|
2022-02-11 02:28:08 +00:00
|
|
|
data = pickle.dumps(p)
|
2016-10-16 17:12:43 +00:00
|
|
|
|
2020-06-10 11:30:41 +00:00
|
|
|
|
|
|
|
.. note::
|
2022-02-11 02:28:08 +00:00
|
|
|
If given, the second argument to ``dumps`` must be 2 or larger - 0 and 1 are
|
|
|
|
not supported. Newer versions are also fine; for instance, specify ``-1`` to
|
|
|
|
always use the latest available version. Beware: failure to follow these
|
|
|
|
instructions will cause important pybind11 memory allocation routines to be
|
|
|
|
skipped during unpickling, which will likely lead to memory corruption
|
feat: remove Python 3.7 support (#5191)
* First pass updating misc files, informed by https://github.com/pybind/pybind11/pull/5177/commits
* Remove jobs using silkeh/clang and gcc docker containers that come with Python 3.7
* Add silkeh/clang:17-bookworm
* Add job using GCC 7
* Revert "Add job using GCC 7"
This reverts commit 518515a761ac37dc2cf5d0980da82d0de39edc28.
* Try running in ubuntu-18.04 container under ubuntu-latest (to get GCC 7)
* Fix `-` vs `:` mixup.
* This reverts commit b1c4304475b8ad129c12330c7ed7eb85d15ba14a.
Revert "Try running in ubuntu:18.04 container under ubuntu-latest (to get GCC 7)"
This reverts commit b203a294bb444fc6ae57a0100fa91dc91b8d3264.
* `git grep 0x03080000` cleanup.
* `git grep -I -E '3\.7'` cleanup.
Removes two changes made under pybind/pybind11#3702
* Revert "`git grep -I -E '3\.7'` cleanup."
This reverts commit bb5b9d187bffbfb61e2977d7eee46b766fa1cce9.
* Remove comments that are evidently incorrect:
```
...
-- The CXX compiler identification is Clang 15.0.7
...
- Found Python: /usr/bin/python3.9 (found suitable version "3.9.2", minimum required is "3.7") found components: Interpreter Development.Module Development.Embed
...
/__w/pybind11/pybind11/include/pybind11/gil.h:150:13: error: 'auto key' can be declared as 'auto *key' [readability-qualified-auto,-warnings-as-errors]
auto key = internals.tstate;
^~~~~
auto *
/__w/pybind11/pybind11/include/pybind11/gil.h:174:13: error: 'auto key' can be declared as 'auto *key' [readability-qualified-auto,-warnings-as-errors]
auto key = detail::get_internals().tstate;
^~~~~
auto *
```
* .github/workflows/configure.yml: Change from Python 3.7 to 3.8
* Misc cleanup pass
* Miscellaneous changes based on manual review of the `git grep` matches below:
```
git_grep_37_38.sh |& sort | uniq -c
```
With git_grep_37_38.sh:
```
set -x
git grep 0x0307
git grep 0x0308
git grep PY_MINOR_VERSION
git grep PYPY_VERSION
git grep -I -E '3\.7'
git grep -I -E '3\.8'
git grep -I -E '\(3, 7'
git grep -I -E '\(3, 8'
git grep -I -E '3[^A-Za-z0-9.]+7'
git grep -I -E '3[^A-Za-z0-9.]+8'
```
Output:
```
1 .appveyor.yml: $env:CMAKE_INCLUDE_PATH = "eigen-3.3.7;$env:CMAKE_INCLUDE_PATH"
1 .appveyor.yml: 7z x eigen-3.3.7.zip -y > $null
1 .appveyor.yml: Start-FileDownload 'https://gitlab.com/libeigen/eigen/-/archive/3.3.7/eigen-3.3.7.zip'
1 CMakeLists.txt: # Bug in macOS CMake < 3.7 is unable to download catch
1 CMakeLists.txt: elseif(WINDOWS AND CMAKE_VERSION VERSION_LESS 3.8)
1 CMakeLists.txt: if(OSX AND CMAKE_VERSION VERSION_LESS 3.7)
1 CMakeLists.txt: message(WARNING "CMAKE 3.7+ needed on macOS to download catch, and newer HIGHLY recommended")
1 CMakeLists.txt: message(WARNING "CMAKE 3.8+ tested on Windows, previous versions untested")
1 CMakeLists.txt: # Only tested with 3.8+ in CI.
1 docs/advanced/functions.rst:Python 3.8 introduced a new positional-only argument syntax, using ``/`` in the
1 docs/changelog.rst:* Adapt pybind11 to a C API convention change in Python 3.8. `#1950
1 docs/changelog.rst:* Allow thread termination to be avoided during shutdown for CPython 3.7+ via
1 docs/changelog.rst: considered as conversion, consistent with Python 3.8+.
1 docs/changelog.rst: CPython 3.8 and 3.9 debug builds.
1 docs/changelog.rst:* Enum now has an ``__index__`` method on Python <3.8 too.
1 docs/changelog.rst: on Python 3.8. `#1780 <https://github.com/pybind/pybind11/pull/1780>`_.
1 docs/changelog.rst:* PyPy 3.10 support was added, PyPy 3.7 support was dropped.
2 docs/changelog.rst:* Support PyPy 7.3.7 and the PyPy3.8 beta. Test python-3.11 on PRs with the
1 docs/changelog.rst:* Use ``macos-13`` (Intel) for CI jobs for now (will drop Python 3.7 soon).
1 docs/changelog.rst:* Use new Python 3.7 Thread Specific Storage (TSS) implementation if available.
1 docs/compiling.rst: cmake -DPYBIND11_PYTHON_VERSION=3.8 ..
1 docs/compiling.rst: find_package(Python 3.8 COMPONENTS Interpreter Development REQUIRED)
1 docs/limitations.rst:- PyPy3 7.3.1 and 7.3.2 have issues with several tests on 32-bit Windows.
1 docs/requirements.txt:idna==3.7 \
1 + git grep 0x0307
1 + git grep 0x0308
1 + git grep -I -E '\(3, 7'
1 + git grep -I -E '3\.7'
1 + git grep -I -E '\(3, 8'
1 + git grep -I -E '3\.8'
1 + git grep -I -E '3[^A-Za-z0-9.]+7'
1 + git grep -I -E '3[^A-Za-z0-9.]+8'
1 + git grep PY_MINOR_VERSION
1 + git grep PYPY_VERSION
2 .github/workflows/ci.yml: - '3.8'
1 .github/workflows/ci.yml: - 3.8
1 .github/workflows/ci.yml: - name: Add Python 3.8
1 .github/workflows/ci.yml: - 'pypy-3.8'
2 .github/workflows/ci.yml: python: '3.8'
1 .github/workflows/ci.yml: - python: '3.8'
1 .github/workflows/ci.yml: - python: 3.8
1 .github/workflows/ci.yml: python: 'pypy-3.8'
1 .github/workflows/configure.yml: cmake: "3.8"
1 .github/workflows/configure.yml: name: 🐍 3.8 • CMake ${{ matrix.cmake }} • ${{ matrix.runs-on }}
1 .github/workflows/configure.yml: - name: Setup Python 3.8
1 .github/workflows/configure.yml: python-version: 3.8
1 .github/workflows/pip.yml: name: 🐍 3.8 • 📦 & 📦 tests • ubuntu-latest
1 .github/workflows/pip.yml: name: 🐍 3.8 • 📦 tests • windows-latest
2 .github/workflows/pip.yml: - name: Setup 🐍 3.8
2 .github/workflows/pip.yml: python-version: 3.8
2 include/pybind11/cast.h:#if !defined(PYPY_VERSION)
2 include/pybind11/cast.h:#if defined(PYPY_VERSION)
2 include/pybind11/cast.h: // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
5 include/pybind11/detail/class.h:#if !defined(PYPY_VERSION)
1 include/pybind11/detail/class.h:#if defined(PYPY_VERSION)
1 include/pybind11/detail/class.h: // This was not needed before Python 3.8 (Python issue 35810)
1 include/pybind11/detail/common.h: && !defined(PYPY_VERSION) && !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
2 include/pybind11/detail/common.h:# error "PYTHON < 3.8 IS UNSUPPORTED. pybind11 v2.13 was the last to support Python 3.7."
1 include/pybind11/detail/common.h:#if defined(PYPY_VERSION) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
1 include/pybind11/detail/common.h:#if PY_VERSION_HEX < 0x03080000
1 include/pybind11/detail/common.h: = PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
1 include/pybind11/detail/internals.h: // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
1 include/pybind11/detail/internals.h:#if PYBIND11_INTERNALS_VERSION <= 4 || defined(PYPY_VERSION)
1 include/pybind11/detail/internals.h:// The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
1 include/pybind11/detail/type_caster_base.h:#if defined(PYPY_VERSION)
1 include/pybind11/embed.h:# define PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX (0x03080000)
1 include/pybind11/embed.h:#if defined(PYPY_VERSION)
1 include/pybind11/eval.h: // globals if not yet present. Python 3.8 made PyRun_String behave
2 include/pybind11/eval.h:#if defined(PYPY_VERSION)
2 include/pybind11/eval.h: // was missing from PyPy3.8 7.3.7.
2 include/pybind11/gil.h: /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
1 include/pybind11/pybind11.h:#if !defined(PYPY_VERSION)
4 include/pybind11/pybind11.h:#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
1 include/pybind11/pytypes.h:#endif //! defined(PYPY_VERSION)
2 include/pybind11/pytypes.h:#if !defined(PYPY_VERSION)
1 include/pybind11/pytypes.h:# if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x07030a00
1 include/pybind11/pytypes.h:#ifdef PYPY_VERSION
1 include/pybind11/stl/filesystem.h:# if !defined(PYPY_VERSION)
2 pybind11/__init__.py:if sys.version_info < (3, 8):
2 pybind11/__init__.py: msg = "pybind11 does not support Python < 3.8. v2.13 was the last release supporting Python 3.7."
1 pyproject.toml:master.py-version = "3.8"
1 pyproject.toml:python_version = "3.8"
1 README.rst:lines of code and depend on Python (3.8+, or PyPy) and the C++
2 README.rst:- Python 3.8+, and PyPy3 7.3 are supported with an implementation-agnostic
1 setup.cfg: Programming Language :: Python :: 3.8
1 setup.cfg:python_requires = >=3.8
1 setup.py:# TODO: use literals & overload (typing extensions or Python 3.8)
1 tests/CMakeLists.txt:if(NOT CMAKE_VERSION VERSION_LESS 3.8)
2 tests/constructor_stats.h:#if defined(PYPY_VERSION)
1 tests/env.py: doesn't work on CPython 3.8.0 with pytest==3.3.2 on Ubuntu 18.04 (#2922).
1 tests/requirements.txt:build~=1.0; python_version>="3.8"
1 tests/requirements.txt:numpy~=1.21.5; platform_python_implementation!="PyPy" and python_version>="3.8" and python_version<"3.10"
1 tests/requirements.txt:numpy~=1.23.0; python_version=="3.8" and platform_python_implementation=="PyPy"
1 tests/test_buffers.py: env.PYPY, reason="PyPy 7.3.7 doesn't clear this anymore", strict=False
1 tests/test_builtin_casters.py: # Before Python 3.8, `PyLong_AsLong` does not pick up on `obj.__index__`,
2 tests/test_builtin_casters.py: if (3, 8) <= sys.version_info < (3, 10) and env.CPYTHON:
4 tests/test_builtin_casters.py: # TODO: PyPy 3.8 does not behave like CPython 3.8 here yet (7.3.7)
1 tests/test_callbacks.py: assert m.test_callback3(z.double) == "func(43) = 86"
2 tests/test_call_policies.cpp:#if !defined(PYPY_VERSION)
1 tests/test_chrono.py: diff = m.test_chrono_float_diff(43.789012, 1.123456)
1 tests/test_constants_and_functions.py: assert m.f3(86) == 89
1 tests/test_eigen_matrix.py: a_copy3[8, 1] = 11
1 tests/test_eigen_matrix.py: assert np.all(cornersc == np.array([[1.0, 3], [7, 9]]))
1 tests/test_eigen_matrix.py: assert np.all(cornersr == np.array([[1.0, 3], [7, 9]]))
1 tests/test_eigen_matrix.py: mymat = chol(np.array([[1.0, 2, 4], [2, 13, 23], [4, 23, 77]]))
1 tests/test_exceptions.py: if hasattr(pytest, unraisable): # Python >= 3.8 and pytest >= 6
2 tests/test_exceptions.py:@pytest.mark.xfail(env.PYPY, reason="Failure on PyPy 3.8 (7.3.7)", strict=False)
1 tests/test_factory_constructors.py: assert [i.alive() for i in cstats] == [13, 7]
1 tests/test_kwargs_and_defaults.cpp:#ifdef PYPY_VERSION
1 tests/test_local_bindings.py: assert i1.get3() == 8
1 tests/test_methods_and_attributes.cpp:#if !defined(PYPY_VERSION)
1 tests/test_numpy_array.py: a = np.arange(3 * 7 * 2) + 1
1 tests/test_numpy_array.py: assert str(excinfo.value) == "cannot reshape array of size 42 into shape (3,7,1)"
2 tests/test_numpy_array.py: assert x.shape == (3, 7, 2)
2 tests/test_numpy_array.py: m.reshape_tuple(a, (3, 7, 1))
2 tests/test_numpy_array.py: x = m.reshape_tuple(a, (3, 7, 2))
1 tests/test_numpy_vectorize.py: assert np.isclose(m.vectorized_func3(np.array(3 + 7j)), [6 + 14j])
1 tests/test_pickling.cpp:#if !defined(PYPY_VERSION)
1 tests/test_pytypes.cpp:#if (defined(__APPLE__) && defined(__clang__)) || defined(PYPY_VERSION)
1 tests/test_smart_ptr.cpp: m.def("make_myobject3_1", []() { return new MyObject3(8); });
1 tests/test_smart_ptr.py: assert cstats.values() == ["MyObject3[9]", "MyObject3[8]", "MyObject3[9]"]
1 tests/test_stl_binders.py: assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 88])
1 tests/test_stl_binders.py: assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 88, 4])
1 tests/test_type_caster_pyobject_ptr.cpp:#if !defined(PYPY_VERSION) // It is not worth the trouble doing something special for PyPy.
1 tools/FindPythonLibsNew.cmake: set(PythonLibsNew_FIND_VERSION "3.8")
1 tools/JoinPaths.cmake:# https://docs.python.org/3.7/library/os.path.html#os.path.join
1 tools/pybind11NewTools.cmake: Python 3.8 REQUIRED COMPONENTS ${_pybind11_interp_component} ${_pybind11_dev_component}
1 tools/pybind11NewTools.cmake:# Python debug libraries expose slightly different objects before 3.8
1 tools/pybind11Tools.cmake: "3.12;3.11;3.10;3.9;3.8"
1 tools/pybind11Tools.cmake: if(NOT DEFINED PYPY_VERSION)
1 tools/pybind11Tools.cmake: message(STATUS "PYPY ${PYPY_VERSION} (Py ${PYTHON_VERSION})")
1 tools/pybind11Tools.cmake:# Python debug libraries expose slightly different objects before 3.8
1 tools/pybind11Tools.cmake: set(PYPY_VERSION
```
* Change `[tool.ruff]` `target-version` to `"py38"`, as suggested by @Skylion007
2024-07-30 16:18:35 +00:00
|
|
|
and/or segmentation faults.
|
2016-10-16 17:12:43 +00:00
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
The file :file:`tests/test_pickling.cpp` contains a complete example
|
|
|
|
that demonstrates how to pickle and unpickle types using pybind11 in more
|
|
|
|
detail.
|
|
|
|
|
|
|
|
.. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances
|
|
|
|
|
2020-06-10 11:30:41 +00:00
|
|
|
Deepcopy support
|
|
|
|
================
|
|
|
|
|
|
|
|
Python normally uses references in assignments. Sometimes a real copy is needed
|
|
|
|
to prevent changing all copies. The ``copy`` module [#f5]_ provides these
|
|
|
|
capabilities.
|
|
|
|
|
2022-02-11 02:28:08 +00:00
|
|
|
A class with pickle support is automatically also (deep)copy
|
2020-06-10 11:30:41 +00:00
|
|
|
compatible. However, performance can be improved by adding custom
|
2022-02-11 02:28:08 +00:00
|
|
|
``__copy__`` and ``__deepcopy__`` methods.
|
2020-06-10 11:30:41 +00:00
|
|
|
|
|
|
|
For simple classes (deep)copy can be enabled by using the copy constructor,
|
|
|
|
which should look as follows:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
py::class_<Copyable>(m, "Copyable")
|
|
|
|
.def("__copy__", [](const Copyable &self) {
|
|
|
|
return Copyable(self);
|
|
|
|
})
|
|
|
|
.def("__deepcopy__", [](const Copyable &self, py::dict) {
|
|
|
|
return Copyable(self);
|
|
|
|
}, "memo"_a);
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
Dynamic attributes will not be copied in this example.
|
|
|
|
|
|
|
|
.. [#f5] https://docs.python.org/3/library/copy.html
|
|
|
|
|
2016-10-16 17:12:43 +00:00
|
|
|
Multiple Inheritance
|
|
|
|
====================
|
|
|
|
|
|
|
|
pybind11 can create bindings for types that derive from multiple base types
|
|
|
|
(aka. *multiple inheritance*). To do so, specify all bases in the template
|
|
|
|
arguments of the ``class_`` declaration:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType")
|
|
|
|
...
|
|
|
|
|
|
|
|
The base types can be specified in arbitrary order, and they can even be
|
|
|
|
interspersed with alias types and holder types (discussed earlier in this
|
|
|
|
document)---pybind11 will automatically find out which is which. The only
|
|
|
|
requirement is that the first template argument is the type to be declared.
|
|
|
|
|
2017-02-23 02:36:09 +00:00
|
|
|
It is also permitted to inherit multiply from exported C++ classes in Python,
|
2018-05-04 15:04:45 +00:00
|
|
|
as well as inheriting from multiple Python and/or pybind11-exported classes.
|
2017-02-23 02:36:09 +00:00
|
|
|
|
|
|
|
There is one caveat regarding the implementation of this feature:
|
|
|
|
|
|
|
|
When only one base type is specified for a C++ type that actually has multiple
|
|
|
|
bases, pybind11 will assume that it does not participate in multiple
|
|
|
|
inheritance, which can lead to undefined behavior. In such cases, add the tag
|
|
|
|
``multiple_inheritance`` to the class constructor:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance());
|
|
|
|
|
|
|
|
The tag is redundant and does not need to be specified when multiple base types
|
|
|
|
are listed.
|
2017-07-29 02:03:44 +00:00
|
|
|
|
|
|
|
.. _module_local:
|
|
|
|
|
|
|
|
Module-local class bindings
|
|
|
|
===========================
|
|
|
|
|
2018-05-04 15:04:45 +00:00
|
|
|
When creating a binding for a class, pybind11 by default makes that binding
|
2017-07-29 02:03:44 +00:00
|
|
|
"global" across modules. What this means is that a type defined in one module
|
2017-08-17 15:38:05 +00:00
|
|
|
can be returned from any module resulting in the same Python type. For
|
2017-07-29 02:03:44 +00:00
|
|
|
example, this allows the following:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
// In the module1.cpp binding code for module1:
|
|
|
|
py::class_<Pet>(m, "Pet")
|
2017-08-17 15:38:05 +00:00
|
|
|
.def(py::init<std::string>())
|
|
|
|
.def_readonly("name", &Pet::name);
|
2017-07-29 02:03:44 +00:00
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
// In the module2.cpp binding code for module2:
|
2017-08-17 15:38:05 +00:00
|
|
|
m.def("create_pet", [](std::string name) { return new Pet(name); });
|
2017-07-29 02:03:44 +00:00
|
|
|
|
|
|
|
.. code-block:: pycon
|
|
|
|
|
|
|
|
>>> from module1 import Pet
|
2017-08-17 15:38:05 +00:00
|
|
|
>>> from module2 import create_pet
|
|
|
|
>>> pet1 = Pet("Kitty")
|
|
|
|
>>> pet2 = create_pet("Doggy")
|
|
|
|
>>> pet2.name()
|
|
|
|
'Doggy'
|
2017-07-29 02:03:44 +00:00
|
|
|
|
|
|
|
When writing binding code for a library, this is usually desirable: this
|
|
|
|
allows, for example, splitting up a complex library into multiple Python
|
|
|
|
modules.
|
|
|
|
|
|
|
|
In some cases, however, this can cause conflicts. For example, suppose two
|
|
|
|
unrelated modules make use of an external C++ library and each provide custom
|
|
|
|
bindings for one of that library's classes. This will result in an error when
|
|
|
|
a Python program attempts to import both modules (directly or indirectly)
|
|
|
|
because of conflicting definitions on the external type:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
// dogs.cpp
|
|
|
|
|
|
|
|
// Binding for external library class:
|
|
|
|
py::class<pets::Pet>(m, "Pet")
|
|
|
|
.def("name", &pets::Pet::name);
|
|
|
|
|
|
|
|
// Binding for local extension class:
|
|
|
|
py::class<Dog, pets::Pet>(m, "Dog")
|
|
|
|
.def(py::init<std::string>());
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
// cats.cpp, in a completely separate project from the above dogs.cpp.
|
|
|
|
|
|
|
|
// Binding for external library class:
|
|
|
|
py::class<pets::Pet>(m, "Pet")
|
|
|
|
.def("get_name", &pets::Pet::name);
|
|
|
|
|
|
|
|
// Binding for local extending class:
|
|
|
|
py::class<Cat, pets::Pet>(m, "Cat")
|
|
|
|
.def(py::init<std::string>());
|
|
|
|
|
|
|
|
.. code-block:: pycon
|
|
|
|
|
|
|
|
>>> import cats
|
|
|
|
>>> import dogs
|
|
|
|
Traceback (most recent call last):
|
|
|
|
File "<stdin>", line 1, in <module>
|
|
|
|
ImportError: generic_type: type "Pet" is already registered!
|
|
|
|
|
|
|
|
To get around this, you can tell pybind11 to keep the external class binding
|
|
|
|
localized to the module by passing the ``py::module_local()`` attribute into
|
|
|
|
the ``py::class_`` constructor:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
// Pet binding in dogs.cpp:
|
|
|
|
py::class<pets::Pet>(m, "Pet", py::module_local())
|
|
|
|
.def("name", &pets::Pet::name);
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
// Pet binding in cats.cpp:
|
|
|
|
py::class<pets::Pet>(m, "Pet", py::module_local())
|
|
|
|
.def("get_name", &pets::Pet::name);
|
|
|
|
|
2017-08-17 15:38:05 +00:00
|
|
|
This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes,
|
|
|
|
avoiding the conflict and allowing both modules to be loaded. C++ code in the
|
|
|
|
``dogs`` module that casts or returns a ``Pet`` instance will result in a
|
|
|
|
``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result
|
|
|
|
in a ``cats.Pet`` Python instance.
|
2017-07-29 02:03:44 +00:00
|
|
|
|
2017-08-17 15:38:05 +00:00
|
|
|
This does come with two caveats, however: First, external modules cannot return
|
|
|
|
or cast a ``Pet`` instance to Python (unless they also provide their own local
|
|
|
|
bindings). Second, from the Python point of view they are two distinct classes.
|
|
|
|
|
|
|
|
Note that the locality only applies in the C++ -> Python direction. When
|
|
|
|
passing such a ``py::module_local`` type into a C++ function, the module-local
|
|
|
|
classes are still considered. This means that if the following function is
|
|
|
|
added to any module (including but not limited to the ``cats`` and ``dogs``
|
|
|
|
modules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet``
|
|
|
|
argument:
|
2017-07-29 02:03:44 +00:00
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
2017-08-17 15:38:05 +00:00
|
|
|
m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); });
|
2017-07-29 02:03:44 +00:00
|
|
|
|
2017-08-17 15:38:05 +00:00
|
|
|
For example, suppose the above function is added to each of ``cats.cpp``,
|
|
|
|
``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that
|
|
|
|
does *not* bind ``Pets`` at all).
|
2017-07-29 02:03:44 +00:00
|
|
|
|
|
|
|
.. code-block:: pycon
|
|
|
|
|
2017-08-17 15:38:05 +00:00
|
|
|
>>> import cats, dogs, frogs # No error because of the added py::module_local()
|
2017-07-29 02:03:44 +00:00
|
|
|
>>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover")
|
2017-08-17 15:38:05 +00:00
|
|
|
>>> (cats.pet_name(mycat), dogs.pet_name(mydog))
|
2017-07-29 02:03:44 +00:00
|
|
|
('Fluffy', 'Rover')
|
2017-08-17 15:38:05 +00:00
|
|
|
>>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat))
|
|
|
|
('Rover', 'Fluffy', 'Fluffy')
|
|
|
|
|
|
|
|
It is possible to use ``py::module_local()`` registrations in one module even
|
|
|
|
if another module registers the same type globally: within the module with the
|
|
|
|
module-local definition, all C++ instances will be cast to the associated bound
|
|
|
|
Python type. In other modules any such values are converted to the global
|
|
|
|
Python type created elsewhere.
|
2017-08-04 17:05:12 +00:00
|
|
|
|
2017-07-29 02:03:44 +00:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`
|
|
|
|
header) apply ``py::module_local`` by default when the bound type might
|
|
|
|
conflict with other modules; see :ref:`stl_bind` for details.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
The localization of the bound types is actually tied to the shared object
|
|
|
|
or binary generated by the compiler/linker. For typical modules created
|
|
|
|
with ``PYBIND11_MODULE()``, this distinction is not significant. It is
|
|
|
|
possible, however, when :ref:`embedding` to embed multiple modules in the
|
|
|
|
same binary (see :ref:`embedding_modules`). In such a case, the
|
|
|
|
localization will apply across all embedded modules within the same binary.
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
The file :file:`tests/test_local_bindings.cpp` contains additional examples
|
|
|
|
that demonstrate how ``py::module_local()`` works.
|
2017-08-17 15:03:46 +00:00
|
|
|
|
|
|
|
Binding protected member functions
|
|
|
|
==================================
|
|
|
|
|
|
|
|
It's normally not possible to expose ``protected`` member functions to Python:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class A {
|
|
|
|
protected:
|
|
|
|
int foo() const { return 42; }
|
|
|
|
};
|
|
|
|
|
|
|
|
py::class_<A>(m, "A")
|
|
|
|
.def("foo", &A::foo); // error: 'foo' is a protected member of 'A'
|
|
|
|
|
|
|
|
On one hand, this is good because non-``public`` members aren't meant to be
|
|
|
|
accessed from the outside. But we may want to make use of ``protected``
|
|
|
|
functions in derived Python classes.
|
|
|
|
|
|
|
|
The following pattern makes this possible:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class A {
|
|
|
|
protected:
|
|
|
|
int foo() const { return 42; }
|
|
|
|
};
|
|
|
|
|
|
|
|
class Publicist : public A { // helper type for exposing protected functions
|
|
|
|
public:
|
|
|
|
using A::foo; // inherited with different access modifier
|
|
|
|
};
|
|
|
|
|
|
|
|
py::class_<A>(m, "A") // bind the primary class
|
|
|
|
.def("foo", &Publicist::foo); // expose protected methods via the publicist
|
|
|
|
|
|
|
|
This works because ``&Publicist::foo`` is exactly the same function as
|
|
|
|
``&A::foo`` (same signature and address), just with a different access
|
|
|
|
modifier. The only purpose of the ``Publicist`` helper class is to make
|
|
|
|
the function name ``public``.
|
|
|
|
|
|
|
|
If the intent is to expose ``protected`` ``virtual`` functions which can be
|
|
|
|
overridden in Python, the publicist pattern can be combined with the previously
|
|
|
|
described trampoline:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class A {
|
|
|
|
public:
|
|
|
|
virtual ~A() = default;
|
|
|
|
|
|
|
|
protected:
|
|
|
|
virtual int foo() const { return 42; }
|
|
|
|
};
|
|
|
|
|
|
|
|
class Trampoline : public A {
|
|
|
|
public:
|
2020-09-15 12:56:20 +00:00
|
|
|
int foo() const override { PYBIND11_OVERRIDE(int, A, foo, ); }
|
2017-08-17 15:03:46 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
class Publicist : public A {
|
|
|
|
public:
|
|
|
|
using A::foo;
|
|
|
|
};
|
|
|
|
|
|
|
|
py::class_<A, Trampoline>(m, "A") // <-- `Trampoline` here
|
|
|
|
.def("foo", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`!
|
|
|
|
|
2020-04-05 06:34:00 +00:00
|
|
|
Binding final classes
|
|
|
|
=====================
|
|
|
|
|
|
|
|
Some classes may not be appropriate to inherit from. In C++11, classes can
|
|
|
|
use the ``final`` specifier to ensure that a class cannot be inherited from.
|
2020-07-20 17:35:21 +00:00
|
|
|
The ``py::is_final`` attribute can be used to ensure that Python classes
|
2020-04-05 06:34:00 +00:00
|
|
|
cannot inherit from a specified type. The underlying C++ type does not need
|
|
|
|
to be declared final.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
class IsFinal final {};
|
|
|
|
|
|
|
|
py::class_<IsFinal>(m, "IsFinal", py::is_final());
|
|
|
|
|
|
|
|
When you try to inherit from such a class in Python, you will now get this
|
|
|
|
error:
|
|
|
|
|
|
|
|
.. code-block:: pycon
|
|
|
|
|
|
|
|
>>> class PyFinalChild(IsFinal):
|
|
|
|
... pass
|
2021-09-22 19:38:50 +00:00
|
|
|
...
|
2020-04-05 06:34:00 +00:00
|
|
|
TypeError: type 'IsFinal' is not an acceptable base type
|
|
|
|
|
|
|
|
.. note:: This attribute is currently ignored on PyPy
|
|
|
|
|
2020-08-19 18:53:59 +00:00
|
|
|
.. versionadded:: 2.6
|
|
|
|
|
2022-01-29 22:38:30 +00:00
|
|
|
Binding classes with template parameters
|
|
|
|
========================================
|
|
|
|
|
|
|
|
pybind11 can also wrap classes that have template parameters. Consider these classes:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
struct Cat {};
|
|
|
|
struct Dog {};
|
|
|
|
|
|
|
|
template <typename PetType>
|
|
|
|
struct Cage {
|
|
|
|
Cage(PetType& pet);
|
|
|
|
PetType& get();
|
|
|
|
};
|
|
|
|
|
|
|
|
C++ templates may only be instantiated at compile time, so pybind11 can only
|
|
|
|
wrap instantiated templated classes. You cannot wrap a non-instantiated template:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
// BROKEN (this will not compile)
|
|
|
|
py::class_<Cage>(m, "Cage");
|
|
|
|
.def("get", &Cage::get);
|
|
|
|
|
|
|
|
You must explicitly specify each template/type combination that you want to
|
|
|
|
wrap separately.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
// ok
|
|
|
|
py::class_<Cage<Cat>>(m, "CatCage")
|
|
|
|
.def("get", &Cage<Cat>::get);
|
|
|
|
|
|
|
|
// ok
|
|
|
|
py::class_<Cage<Dog>>(m, "DogCage")
|
|
|
|
.def("get", &Cage<Dog>::get);
|
|
|
|
|
|
|
|
If your class methods have template parameters you can wrap those as well,
|
|
|
|
but once again each instantiation must be explicitly specified:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
typename <typename T>
|
|
|
|
struct MyClass {
|
|
|
|
template <typename V>
|
|
|
|
T fn(V v);
|
|
|
|
};
|
|
|
|
|
|
|
|
py::class<MyClass<int>>(m, "MyClassT")
|
|
|
|
.def("fn", &MyClass<int>::fn<std::string>);
|
|
|
|
|
2018-04-14 00:13:10 +00:00
|
|
|
Custom automatic downcasters
|
|
|
|
============================
|
|
|
|
|
|
|
|
As explained in :ref:`inheritance`, pybind11 comes with built-in
|
|
|
|
understanding of the dynamic type of polymorphic objects in C++; that
|
|
|
|
is, returning a Pet to Python produces a Python object that knows it's
|
|
|
|
wrapping a Dog, if Pet has virtual methods and pybind11 knows about
|
|
|
|
Dog and this Pet is in fact a Dog. Sometimes, you might want to
|
|
|
|
provide this automatic downcasting behavior when creating bindings for
|
|
|
|
a class hierarchy that does not use standard C++ polymorphism, such as
|
|
|
|
LLVM [#f4]_. As long as there's some way to determine at runtime
|
|
|
|
whether a downcast is safe, you can proceed by specializing the
|
|
|
|
``pybind11::polymorphic_type_hook`` template:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
enum class PetKind { Cat, Dog, Zebra };
|
|
|
|
struct Pet { // Not polymorphic: has no virtual methods
|
|
|
|
const PetKind kind;
|
|
|
|
int age = 0;
|
|
|
|
protected:
|
|
|
|
Pet(PetKind _kind) : kind(_kind) {}
|
|
|
|
};
|
|
|
|
struct Dog : Pet {
|
|
|
|
Dog() : Pet(PetKind::Dog) {}
|
|
|
|
std::string sound = "woof!";
|
|
|
|
std::string bark() const { return sound; }
|
|
|
|
};
|
|
|
|
|
2022-08-01 18:31:31 +00:00
|
|
|
namespace PYBIND11_NAMESPACE {
|
2018-04-14 00:13:10 +00:00
|
|
|
template<> struct polymorphic_type_hook<Pet> {
|
|
|
|
static const void *get(const Pet *src, const std::type_info*& type) {
|
|
|
|
// note that src may be nullptr
|
|
|
|
if (src && src->kind == PetKind::Dog) {
|
|
|
|
type = &typeid(Dog);
|
|
|
|
return static_cast<const Dog*>(src);
|
|
|
|
}
|
|
|
|
return src;
|
|
|
|
}
|
|
|
|
};
|
2022-08-01 18:31:31 +00:00
|
|
|
} // namespace PYBIND11_NAMESPACE
|
2018-04-14 00:13:10 +00:00
|
|
|
|
|
|
|
When pybind11 wants to convert a C++ pointer of type ``Base*`` to a
|
|
|
|
Python object, it calls ``polymorphic_type_hook<Base>::get()`` to
|
|
|
|
determine if a downcast is possible. The ``get()`` function should use
|
|
|
|
whatever runtime information is available to determine if its ``src``
|
|
|
|
parameter is in fact an instance of some class ``Derived`` that
|
|
|
|
inherits from ``Base``. If it finds such a ``Derived``, it sets ``type
|
|
|
|
= &typeid(Derived)`` and returns a pointer to the ``Derived`` object
|
|
|
|
that contains ``src``. Otherwise, it just returns ``src``, leaving
|
|
|
|
``type`` at its default value of nullptr. If you set ``type`` to a
|
|
|
|
type that pybind11 doesn't know about, no downcasting will occur, and
|
|
|
|
the original ``src`` pointer will be used with its static type
|
|
|
|
``Base*``.
|
|
|
|
|
|
|
|
It is critical that the returned pointer and ``type`` argument of
|
|
|
|
``get()`` agree with each other: if ``type`` is set to something
|
|
|
|
non-null, the returned pointer must point to the start of an object
|
|
|
|
whose type is ``type``. If the hierarchy being exposed uses only
|
|
|
|
single inheritance, a simple ``return src;`` will achieve this just
|
|
|
|
fine, but in the general case, you must cast ``src`` to the
|
|
|
|
appropriate derived-class pointer (e.g. using
|
|
|
|
``static_cast<Derived>(src)``) before allowing it to be returned as a
|
|
|
|
``void*``.
|
|
|
|
|
|
|
|
.. [#f4] https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
pybind11's standard support for downcasting objects whose types
|
|
|
|
have virtual methods is implemented using
|
|
|
|
``polymorphic_type_hook`` too, using the standard C++ ability to
|
|
|
|
determine the most-derived type of a polymorphic object using
|
|
|
|
``typeid()`` and to cast a base pointer to that most-derived type
|
|
|
|
(even if you don't know what it is) using ``dynamic_cast<void*>``.
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
The file :file:`tests/test_tagbased_polymorphic.cpp` contains a
|
|
|
|
more complete example, including a demonstration of how to provide
|
|
|
|
automatic downcasting for an entire class hierarchy without
|
|
|
|
writing one get() function for each class.
|
2020-09-14 22:06:26 +00:00
|
|
|
|
|
|
|
Accessing the type object
|
|
|
|
=========================
|
|
|
|
|
|
|
|
You can get the type object from a C++ class that has already been registered using:
|
|
|
|
|
2021-09-22 19:38:50 +00:00
|
|
|
.. code-block:: cpp
|
2020-09-14 22:06:26 +00:00
|
|
|
|
|
|
|
py::type T_py = py::type::of<T>();
|
|
|
|
|
|
|
|
You can directly use ``py::type::of(ob)`` to get the type object from any python
|
|
|
|
object, just like ``type(ob)`` in Python.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
Other types, like ``py::type::of<int>()``, do not work, see :ref:`type-conversions`.
|
|
|
|
|
|
|
|
.. versionadded:: 2.6
|
2021-09-24 19:08:22 +00:00
|
|
|
|
|
|
|
Custom type setup
|
|
|
|
=================
|
|
|
|
|
|
|
|
For advanced use cases, such as enabling garbage collection support, you may
|
2021-10-08 12:38:04 +00:00
|
|
|
wish to directly manipulate the ``PyHeapTypeObject`` corresponding to a
|
2021-09-24 19:08:22 +00:00
|
|
|
``py::class_`` definition.
|
|
|
|
|
|
|
|
You can do that using ``py::custom_type_setup``:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
struct OwnsPythonObjects {
|
|
|
|
py::object value = py::none();
|
|
|
|
};
|
|
|
|
py::class_<OwnsPythonObjects> cls(
|
|
|
|
m, "OwnsPythonObjects", py::custom_type_setup([](PyHeapTypeObject *heap_type) {
|
|
|
|
auto *type = &heap_type->ht_type;
|
|
|
|
type->tp_flags |= Py_TPFLAGS_HAVE_GC;
|
|
|
|
type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) {
|
|
|
|
auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
|
|
|
|
Py_VISIT(self.value.ptr());
|
|
|
|
return 0;
|
|
|
|
};
|
|
|
|
type->tp_clear = [](PyObject *self_base) {
|
|
|
|
auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
|
|
|
|
self.value = py::none();
|
|
|
|
return 0;
|
|
|
|
};
|
|
|
|
}));
|
|
|
|
cls.def(py::init<>());
|
|
|
|
cls.def_readwrite("value", &OwnsPythonObjects::value);
|
|
|
|
|
|
|
|
.. versionadded:: 2.8
|