Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call the destructor or when is it automatically called from python in pybind11?

Tags:

pybind11

If I am using the take_ownership return value policy in pybind11, and I invoke a function that returns, say, a std::vector<Dog>, how can I ensure that the vector and its contents' destructors are called? Does it have anything to do with going out of scope in the python client code?

like image 207
tacos_tacos_tacos Avatar asked Oct 28 '25 09:10

tacos_tacos_tacos


1 Answers

Things will be destructed when Python garbage collects the object (and invokes the CPython API hooks).

See here for Python docs:

https://docs.python.org/3.7/reference/datamodel.html#objects-values-and-types https://docs.python.org/3.7/reference/datamodel.html#object.del

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. [...]

Specific to pybind, here're the dellocation bits that are invoked upon deletion:

  1. https://github.com/pybind/pybind11/blob/25abf7e/include/pybind11/detail/class.h#L389
  2. https://github.com/pybind/pybind11/blob/25abf7e/include/pybind11/detail/class.h#L346
  3. https://github.com/pybind/pybind11/blob/25abf7e/include/pybind11/detail/class.h#L327
  4. https://github.com/pybind/pybind11/blob/25abf7e/include/pybind11/pybind11.h#L1339
like image 104
eacousineau Avatar answered Oct 30 '25 15:10

eacousineau