class.h
Go to the documentation of this file.
1 /*
2  pybind11/detail/class.h: Python C API implementation details for py::class_
3 
4  Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6  All rights reserved. Use of this source code is governed by a
7  BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #pragma once
11 
12 #include <pybind11/attr.h>
13 #include <pybind11/options.h>
14 
15 #include "exception_translation.h"
16 
19 
20 #if !defined(PYPY_VERSION)
21 # define PYBIND11_BUILTIN_QUALNAME
22 # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
23 #else
24 // In PyPy, we still set __qualname__ so that we can produce reliable function type
25 // signatures; in CPython this macro expands to nothing:
26 # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \
27  setattr((PyObject *) obj, "__qualname__", nameobj)
28 #endif
29 
30 inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
31 #if !defined(PYPY_VERSION)
32  return type->tp_name;
33 #else
34  auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
36  return type->tp_name;
37  else
38  return std::move(module_name) + "." + type->tp_name;
39 #endif
40 }
41 
42 inline PyTypeObject *type_incref(PyTypeObject *type) {
43  Py_INCREF(type);
44  return type;
45 }
46 
47 #if !defined(PYPY_VERSION)
48 
50 extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
51  return PyProperty_Type.tp_descr_get(self, cls, cls);
52 }
53 
55 extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
56  PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
57  return PyProperty_Type.tp_descr_set(self, cls, value);
58 }
59 
60 // Forward declaration to use in `make_static_property_type()`
61 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
62 
66 inline PyTypeObject *make_static_property_type() {
67  constexpr auto *name = "pybind11_static_property";
68  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
69 
70  /* Danger zone: from now (and until PyType_Ready), make sure to
71  issue no Python C API calls which could potentially invoke the
72  garbage collector (the GC will call type_traverse(), which will in
73  turn find the newly constructed type in an invalid state) */
74  auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
75  if (!heap_type) {
76  pybind11_fail("make_static_property_type(): error allocating type!");
77  }
78 
79  heap_type->ht_name = name_obj.inc_ref().ptr();
80 # ifdef PYBIND11_BUILTIN_QUALNAME
81  heap_type->ht_qualname = name_obj.inc_ref().ptr();
82 # endif
83 
84  auto *type = &heap_type->ht_type;
85  type->tp_name = name;
86  type->tp_base = type_incref(&PyProperty_Type);
87  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
88  type->tp_descr_get = pybind11_static_get;
89  type->tp_descr_set = pybind11_static_set;
90 
91 # if PY_VERSION_HEX >= 0x030C0000
92  // Since Python-3.12 property-derived types are required to
93  // have dynamic attributes (to set `__doc__`)
94  enable_dynamic_attributes(heap_type);
95 # endif
96 
97  if (PyType_Ready(type) < 0) {
98  pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
99  }
100 
101  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
103 
104  return type;
105 }
106 
107 #else // PYPY
108 
112 inline PyTypeObject *make_static_property_type() {
113  auto d = dict();
114  PyObject *result = PyRun_String(R"(\
115 class pybind11_static_property(property):
116  def __get__(self, obj, cls):
117  return property.__get__(self, cls, cls)
118 
119  def __set__(self, obj, value):
120  cls = obj if isinstance(obj, type) else type(obj)
121  property.__set__(self, cls, value)
122 )",
123  Py_file_input,
124  d.ptr(),
125  d.ptr());
126  if (result == nullptr)
127  throw error_already_set();
128  Py_DECREF(result);
129  return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
130 }
131 
132 #endif // PYPY
133 
138 extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
139  // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
140  // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
141  PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
142 
143  // The following assignment combinations are possible:
144  // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
145  // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
146  // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
147  auto *const static_prop = (PyObject *) get_internals().static_property_type;
148  const auto call_descr_set = (descr != nullptr) && (value != nullptr)
149  && (PyObject_IsInstance(descr, static_prop) != 0)
150  && (PyObject_IsInstance(value, static_prop) == 0);
151  if (call_descr_set) {
152  // Call `static_property.__set__()` instead of replacing the `static_property`.
153 #if !defined(PYPY_VERSION)
154  return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
155 #else
156  if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
157  Py_DECREF(result);
158  return 0;
159  } else {
160  return -1;
161  }
162 #endif
163  } else {
164  // Replace existing attribute.
165  return PyType_Type.tp_setattro(obj, name, value);
166  }
167 }
168 
175 extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
176  PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
177  if (descr && PyInstanceMethod_Check(descr)) {
178  Py_INCREF(descr);
179  return descr;
180  }
181  return PyType_Type.tp_getattro(obj, name);
182 }
183 
185 extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
186 
187  // use the default metaclass call to create/initialize the object
188  PyObject *self = PyType_Type.tp_call(type, args, kwargs);
189  if (self == nullptr) {
190  return nullptr;
191  }
192 
193  // Ensure that the base __init__ function(s) were called
194  values_and_holders vhs(self);
195  for (const auto &vh : vhs) {
196  if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) {
197  PyErr_Format(PyExc_TypeError,
198  "%.200s.__init__() must be called when overriding __init__",
199  get_fully_qualified_tp_name(vh.type->type).c_str());
200  Py_DECREF(self);
201  return nullptr;
202  }
203  }
204 
205  return self;
206 }
207 
209 extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
211  auto *type = (PyTypeObject *) obj;
212 
213  // A pybind11-registered type will:
214  // 1) be found in internals.registered_types_py
215  // 2) have exactly one associated `detail::type_info`
216  auto found_type = internals.registered_types_py.find(type);
217  if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
218  && found_type->second[0]->type == type) {
219 
220  auto *tinfo = found_type->second[0];
221  auto tindex = std::type_index(*tinfo->cpptype);
222  internals.direct_conversions.erase(tindex);
223 
224  if (tinfo->module_local) {
226  } else {
227  internals.registered_types_cpp.erase(tindex);
228  }
229  internals.registered_types_py.erase(tinfo->type);
230 
231  // Actually just `std::erase_if`, but that's only available in C++20
232  auto &cache = internals.inactive_override_cache;
233  for (auto it = cache.begin(), last = cache.end(); it != last;) {
234  if (it->first == (PyObject *) tinfo->type) {
235  it = cache.erase(it);
236  } else {
237  ++it;
238  }
239  }
240 
241  delete tinfo;
242  }
243  });
244 
245  PyType_Type.tp_dealloc(obj);
246 }
247 
251 inline PyTypeObject *make_default_metaclass() {
252  constexpr auto *name = "pybind11_type";
253  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
254 
255  /* Danger zone: from now (and until PyType_Ready), make sure to
256  issue no Python C API calls which could potentially invoke the
257  garbage collector (the GC will call type_traverse(), which will in
258  turn find the newly constructed type in an invalid state) */
259  auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
260  if (!heap_type) {
261  pybind11_fail("make_default_metaclass(): error allocating metaclass!");
262  }
263 
264  heap_type->ht_name = name_obj.inc_ref().ptr();
265 #ifdef PYBIND11_BUILTIN_QUALNAME
266  heap_type->ht_qualname = name_obj.inc_ref().ptr();
267 #endif
268 
269  auto *type = &heap_type->ht_type;
270  type->tp_name = name;
271  type->tp_base = type_incref(&PyType_Type);
272  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
273 
274  type->tp_call = pybind11_meta_call;
275 
276  type->tp_setattro = pybind11_meta_setattro;
277  type->tp_getattro = pybind11_meta_getattro;
278 
279  type->tp_dealloc = pybind11_meta_dealloc;
280 
281  if (PyType_Ready(type) < 0) {
282  pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
283  }
284 
285  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
287 
288  return type;
289 }
290 
295 inline void traverse_offset_bases(void *valueptr,
296  const detail::type_info *tinfo,
297  instance *self,
298  bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
299  for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
300  if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
301  for (auto &c : parent_tinfo->implicit_casts) {
302  if (c.first == tinfo->cpptype) {
303  auto *parentptr = c.second(valueptr);
304  if (parentptr != valueptr) {
305  f(parentptr, self);
306  }
307  traverse_offset_bases(parentptr, parent_tinfo, self, f);
308  break;
309  }
310  }
311  }
312  }
313 }
314 
315 inline bool register_instance_impl(void *ptr, instance *self) {
316  with_instance_map(ptr, [&](instance_map &instances) { instances.emplace(ptr, self); });
317  return true; // unused, but gives the same signature as the deregister func
318 }
319 inline bool deregister_instance_impl(void *ptr, instance *self) {
320  return with_instance_map(ptr, [&](instance_map &instances) {
321  auto range = instances.equal_range(ptr);
322  for (auto it = range.first; it != range.second; ++it) {
323  if (self == it->second) {
324  instances.erase(it);
325  return true;
326  }
327  }
328  return false;
329  });
330 }
331 
332 inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
333  register_instance_impl(valptr, self);
334  if (!tinfo->simple_ancestors) {
335  traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
336  }
337 }
338 
339 inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
340  bool ret = deregister_instance_impl(valptr, self);
341  if (!tinfo->simple_ancestors) {
342  traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
343  }
344  return ret;
345 }
346 
350 inline PyObject *make_new_instance(PyTypeObject *type) {
351 #if defined(PYPY_VERSION)
352  // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
353  // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
354  ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
355  if (type->tp_basicsize < instance_size) {
356  type->tp_basicsize = instance_size;
357  }
358 #endif
359  PyObject *self = type->tp_alloc(type, 0);
360  auto *inst = reinterpret_cast<instance *>(self);
361  // Allocate the value/holder internals:
362  inst->allocate_layout();
363 
364  return self;
365 }
366 
369 extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
370  return make_new_instance(type);
371 }
372 
376 extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
377  PyTypeObject *type = Py_TYPE(self);
378  std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
379  set_error(PyExc_TypeError, msg.c_str());
380  return -1;
381 }
382 
383 inline void add_patient(PyObject *nurse, PyObject *patient) {
384  auto *instance = reinterpret_cast<detail::instance *>(nurse);
385  instance->has_patients = true;
386  Py_INCREF(patient);
387 
388  with_internals([&](internals &internals) { internals.patients[nurse].push_back(patient); });
389 }
390 
391 inline void clear_patients(PyObject *self) {
392  auto *instance = reinterpret_cast<detail::instance *>(self);
393  std::vector<PyObject *> patients;
394 
396  auto pos = internals.patients.find(self);
397 
398  if (pos == internals.patients.end()) {
399  pybind11_fail(
400  "FATAL: Internal consistency check failed: Invalid clear_patients() call.");
401  }
402 
403  // Clearing the patients can cause more Python code to run, which
404  // can invalidate the iterator. Extract the vector of patients
405  // from the unordered_map first.
406  patients = std::move(pos->second);
407  internals.patients.erase(pos);
408  });
409 
410  instance->has_patients = false;
411  for (PyObject *&patient : patients) {
412  Py_CLEAR(patient);
413  }
414 }
415 
418 inline void clear_instance(PyObject *self) {
419  auto *instance = reinterpret_cast<detail::instance *>(self);
420 
421  // Deallocate any values/holders, if present:
422  for (auto &v_h : values_and_holders(instance)) {
423  if (v_h) {
424 
425  // We have to deregister before we call dealloc because, for virtual MI types, we still
426  // need to be able to get the parent pointers.
427  if (v_h.instance_registered()
428  && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
430  "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
431  }
432 
433  if (instance->owned || v_h.holder_constructed()) {
434  v_h.type->dealloc(v_h);
435  }
436  }
437  }
438  // Deallocate the value/holder layout internals:
440 
441  if (instance->weakrefs) {
442  PyObject_ClearWeakRefs(self);
443  }
444 
445  PyObject **dict_ptr = _PyObject_GetDictPtr(self);
446  if (dict_ptr) {
447  Py_CLEAR(*dict_ptr);
448  }
449 
450  if (instance->has_patients) {
451  clear_patients(self);
452  }
453 }
454 
457 extern "C" inline void pybind11_object_dealloc(PyObject *self) {
458  auto *type = Py_TYPE(self);
459 
460  // If this is a GC tracked object, untrack it first
461  // Note that the track call is implicitly done by the
462  // default tp_alloc, which we never override.
463  if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
464  PyObject_GC_UnTrack(self);
465  }
466 
467  clear_instance(self);
468 
469  type->tp_free(self);
470 
471 #if PY_VERSION_HEX < 0x03080000
472  // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
473  // as part of a derived type's dealloc, in which case we're not allowed to decref
474  // the type here. For cross-module compatibility, we shouldn't compare directly
475  // with `pybind11_object_dealloc`, but with the common one stashed in internals.
476  auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
477  if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
478  Py_DECREF(type);
479 #else
480  // This was not needed before Python 3.8 (Python issue 35810)
481  // https://github.com/pybind/pybind11/issues/1946
482  Py_DECREF(type);
483 #endif
484 }
485 
486 std::string error_string();
487 
491 inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
492  constexpr auto *name = "pybind11_object";
493  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
494 
495  /* Danger zone: from now (and until PyType_Ready), make sure to
496  issue no Python C API calls which could potentially invoke the
497  garbage collector (the GC will call type_traverse(), which will in
498  turn find the newly constructed type in an invalid state) */
499  auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
500  if (!heap_type) {
501  pybind11_fail("make_object_base_type(): error allocating type!");
502  }
503 
504  heap_type->ht_name = name_obj.inc_ref().ptr();
505 #ifdef PYBIND11_BUILTIN_QUALNAME
506  heap_type->ht_qualname = name_obj.inc_ref().ptr();
507 #endif
508 
509  auto *type = &heap_type->ht_type;
510  type->tp_name = name;
511  type->tp_base = type_incref(&PyBaseObject_Type);
512  type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
513  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
514 
515  type->tp_new = pybind11_object_new;
516  type->tp_init = pybind11_object_init;
517  type->tp_dealloc = pybind11_object_dealloc;
518 
519  /* Support weak references (needed for the keep_alive feature) */
520  type->tp_weaklistoffset = offsetof(instance, weakrefs);
521 
522  if (PyType_Ready(type) < 0) {
523  pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
524  }
525 
526  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
528 
529  assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
530  return (PyObject *) heap_type;
531 }
532 
534 extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
535 #if PY_VERSION_HEX >= 0x030D0000
536  PyObject_VisitManagedDict(self, visit, arg);
537 #else
538  PyObject *&dict = *_PyObject_GetDictPtr(self);
539  Py_VISIT(dict);
540 #endif
541 // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
542 #if PY_VERSION_HEX >= 0x03090000
543  Py_VISIT(Py_TYPE(self));
544 #endif
545  return 0;
546 }
547 
549 extern "C" inline int pybind11_clear(PyObject *self) {
550 #if PY_VERSION_HEX >= 0x030D0000
551  PyObject_ClearManagedDict(self);
552 #else
553  PyObject *&dict = *_PyObject_GetDictPtr(self);
554  Py_CLEAR(dict);
555 #endif
556  return 0;
557 }
558 
560 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
561  auto *type = &heap_type->ht_type;
562  type->tp_flags |= Py_TPFLAGS_HAVE_GC;
563 #if PY_VERSION_HEX < 0x030B0000
564  type->tp_dictoffset = type->tp_basicsize; // place dict at the end
565  type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
566 #else
567  type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
568 #endif
569  type->tp_traverse = pybind11_traverse;
570  type->tp_clear = pybind11_clear;
571 
572  static PyGetSetDef getset[]
573  = {{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, nullptr, nullptr},
574  {nullptr, nullptr, nullptr, nullptr, nullptr}};
575  type->tp_getset = getset;
576 }
577 
579 extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
580  // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
581  type_info *tinfo = nullptr;
582  for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
583  tinfo = get_type_info((PyTypeObject *) type.ptr());
584  if (tinfo && tinfo->get_buffer) {
585  break;
586  }
587  }
588  if (view == nullptr || !tinfo || !tinfo->get_buffer) {
589  if (view) {
590  view->obj = nullptr;
591  }
592  set_error(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
593  return -1;
594  }
595  std::memset(view, 0, sizeof(Py_buffer));
596  buffer_info *info = nullptr;
597  try {
598  info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
599  } catch (...) {
601  raise_from(PyExc_BufferError, "Error getting buffer");
602  return -1;
603  }
604  if (info == nullptr) {
605  pybind11_fail("FATAL UNEXPECTED SITUATION: tinfo->get_buffer() returned nullptr.");
606  }
607 
608  if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
609  delete info;
610  // view->obj = nullptr; // Was just memset to 0, so not necessary
611  set_error(PyExc_BufferError, "Writable buffer requested for readonly storage");
612  return -1;
613  }
614  view->obj = obj;
615  view->ndim = 1;
616  view->internal = info;
617  view->buf = info->ptr;
618  view->itemsize = info->itemsize;
619  view->len = view->itemsize;
620  for (auto s : info->shape) {
621  view->len *= s;
622  }
623  view->readonly = static_cast<int>(info->readonly);
624  if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
625  view->format = const_cast<char *>(info->format.c_str());
626  }
627  if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
628  view->ndim = (int) info->ndim;
629  view->strides = info->strides.data();
630  view->shape = info->shape.data();
631  }
632  Py_INCREF(view->obj);
633  return 0;
634 }
635 
637 extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
638  delete (buffer_info *) view->internal;
639 }
640 
642 inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
643  heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
644 
645  heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
646  heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
647 }
648 
651 inline PyObject *make_new_python_type(const type_record &rec) {
652  auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
653 
654  auto qualname = name;
655  if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
656  qualname = reinterpret_steal<object>(
657  PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
658  }
659 
660  object module_;
661  if (rec.scope) {
662  if (hasattr(rec.scope, "__module__")) {
663  module_ = rec.scope.attr("__module__");
664  } else if (hasattr(rec.scope, "__name__")) {
665  module_ = rec.scope.attr("__name__");
666  }
667  }
668 
669  const auto *full_name = c_str(
670 #if !defined(PYPY_VERSION)
671  module_ ? str(module_).cast<std::string>() + "." + rec.name :
672 #endif
673  rec.name);
674 
675  char *tp_doc = nullptr;
677  /* Allocate memory for docstring (Python will free this later on) */
678  size_t size = std::strlen(rec.doc) + 1;
679 #if PY_VERSION_HEX >= 0x030D0000
680  tp_doc = (char *) PyMem_MALLOC(size);
681 #else
682  tp_doc = (char *) PyObject_MALLOC(size);
683 #endif
684  std::memcpy((void *) tp_doc, rec.doc, size);
685  }
686 
687  auto &internals = get_internals();
688  auto bases = tuple(rec.bases);
689  auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
690 
691  /* Danger zone: from now (and until PyType_Ready), make sure to
692  issue no Python C API calls which could potentially invoke the
693  garbage collector (the GC will call type_traverse(), which will in
694  turn find the newly constructed type in an invalid state) */
695  auto *metaclass
696  = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
697 
698  auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
699  if (!heap_type) {
700  pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
701  }
702 
703  heap_type->ht_name = name.release().ptr();
704 #ifdef PYBIND11_BUILTIN_QUALNAME
705  heap_type->ht_qualname = qualname.inc_ref().ptr();
706 #endif
707 
708  auto *type = &heap_type->ht_type;
709  type->tp_name = full_name;
710  type->tp_doc = tp_doc;
711  type->tp_base = type_incref((PyTypeObject *) base);
712  type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
713  if (!bases.empty()) {
714  type->tp_bases = bases.release().ptr();
715  }
716 
717  /* Don't inherit base __init__ */
718  type->tp_init = pybind11_object_init;
719 
720  /* Supported protocols */
721  type->tp_as_number = &heap_type->as_number;
722  type->tp_as_sequence = &heap_type->as_sequence;
723  type->tp_as_mapping = &heap_type->as_mapping;
724  type->tp_as_async = &heap_type->as_async;
725 
726  /* Flags */
727  type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
728  if (!rec.is_final) {
729  type->tp_flags |= Py_TPFLAGS_BASETYPE;
730  }
731 
732  if (rec.dynamic_attr) {
733  enable_dynamic_attributes(heap_type);
734  }
735 
736  if (rec.buffer_protocol) {
737  enable_buffer_protocol(heap_type);
738  }
739 
740  if (rec.custom_type_setup_callback) {
741  rec.custom_type_setup_callback(heap_type);
742  }
743 
744  if (PyType_Ready(type) < 0) {
745  pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
746  }
747 
748  assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
749 
750  /* Register type with the parent scope */
751  if (rec.scope) {
752  setattr(rec.scope, rec.name, (PyObject *) type);
753  } else {
754  Py_INCREF(type); // Keep it alive forever (reference leak)
755  }
756 
757  if (module_) { // Needed by pydoc
758  setattr((PyObject *) type, "__module__", module_);
759  }
760 
762 
763  return (PyObject *) type;
764 }
765 
gtsam.examples.DogLegOptimizerExample.int
int
Definition: DogLegOptimizerExample.py:111
type_record::doc
const char * doc
Optional docstring.
Definition: attr.h:308
deregister_instance
bool deregister_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:339
attr.h
name
Annotation for function names.
Definition: attr.h:51
pybind11_object_init
int pybind11_object_init(PyObject *self, PyObject *, PyObject *)
Definition: class.h:376
setattr
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:922
pybind11_static_set
int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value)
pybind11_static_property.__set__(): Just like the above __get__().
Definition: class.h:55
internals
Definition: internals.h:177
base
Annotation indicating that a class derives from another given type.
Definition: attr.h:64
with_instance_map
auto with_instance_map(const void *ptr, const F &cb) -> decltype(cb(std::declval< instance_map & >()))
Definition: internals.h:656
clear_patients
void clear_patients(PyObject *self)
Definition: class.h:391
add_patient
void add_patient(PyObject *nurse, PyObject *patient)
Definition: class.h:383
traverse_offset_bases
void traverse_offset_bases(void *valueptr, const detail::type_info *tinfo, instance *self, bool(*f)(void *, instance *))
Definition: class.h:295
gtsam.examples.DogLegOptimizerExample.type
type
Definition: DogLegOptimizerExample.py:111
ssize_t
Py_ssize_t ssize_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:508
error_already_set
Definition: pytypes.h:739
type_info
Definition: internals.h:241
kwargs
Definition: pytypes.h:2215
s
RealScalar s
Definition: level1_cplx_impl.h:126
d
static const double d[K][N]
Definition: igam.h:11
type_record::dynamic_attr
bool dynamic_attr
Does the class manage a dict?
Definition: attr.h:320
internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:182
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
type_info::get_buffer_data
void * get_buffer_data
Definition: internals.h:252
ret
DenseIndex ret
Definition: level1_cplx_impl.h:44
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:870
type
Definition: pytypes.h:1527
enable_dynamic_attributes
void enable_dynamic_attributes(PyHeapTypeObject *heap_type)
Give instances of this type a __dict__ and opt into garbage collection.
Definition: class.h:560
detail
Definition: testSerializationNonlinear.cpp:69
internals::static_property_type
PyTypeObject * static_property_type
Definition: internals.h:203
options.h
type_record::name
const char * name
Name of the class.
Definition: attr.h:281
get_internals
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:500
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
h
const double h
Definition: testSimpleHelicopter.cpp:19
make_static_property_type
PyTypeObject * make_static_property_type()
Definition: class.h:66
Eigen::last
static const symbolic::SymbolExpr< internal::symbolic_last_tag > last
Definition: IndexedViewHelper.h:38
result
Values result
Definition: OdometryOptimize.cpp:8
descr
Definition: descr.h:25
PYBIND11_FROM_STRING
#define PYBIND11_FROM_STRING
Definition: wrap/pybind11/include/pybind11/detail/common.h:373
make_new_instance
PyObject * make_new_instance(PyTypeObject *type)
Definition: class.h:350
deregister_instance_impl
bool deregister_instance_impl(void *ptr, instance *self)
Definition: class.h:319
name
static char name[]
Definition: rgamma.c:72
size
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
make_object_base_type
PyObject * make_object_base_type(PyTypeObject *metaclass)
Definition: class.h:491
internals::instance_base
PyObject * instance_base
Definition: internals.h:205
PYBIND11_SET_OLDPY_QUALNAME
#define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
Definition: class.h:22
instance
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Definition: wrap/pybind11/include/pybind11/detail/common.h:602
gtsam::range
Double_ range(const Point2_ &p, const Point2_ &q)
Definition: slam/expressions.h:30
view
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set set pointsize set encoding default set nopolar set noparametric set view
Definition: gnuplot_common_settings.hh:27
type_record::metaclass
handle metaclass
Custom metaclass (optional)
Definition: attr.h:311
matlab_wrap.module_name
module_name
Definition: matlab_wrap.py:60
dict
Definition: pytypes.h:2109
try_translate_exceptions
void try_translate_exceptions()
Definition: exception_translation.h:36
raise_from
void raise_from(PyObject *type, const char *message)
Definition: pytypes.h:797
get_fully_qualified_tp_name
std::string get_fully_qualified_tp_name(PyTypeObject *type)
Definition: class.h:30
pybind11_meta_dealloc
void pybind11_meta_dealloc(PyObject *obj)
Cleanup the type-info for a pybind11-registered type.
Definition: class.h:209
handle
Definition: pytypes.h:226
handle::cast
T cast() const
Definition: cast.h:1241
conf.release
release
Definition: gtsam/3rdparty/GeographicLib/python/doc/conf.py:69
instance_map
std::unordered_multimap< const void *, instance * > instance_map
Definition: internals.h:149
internals::inactive_override_cache
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:192
exception_translation.h
pybind11_object_new
PyObject * pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *)
Definition: class.h:369
type_record::bases
list bases
List of base classes of the newly created type.
Definition: attr.h:305
object::release
handle release()
Definition: pytypes.h:385
metaclass
Annotation which requests that a special metaclass is created for a type.
Definition: attr.h:85
local_internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:584
type_record
Special data structure which (temporarily) holds metadata about a bound class.
Definition: attr.h:272
instance::deallocate_layout
void deallocate_layout()
Destroys/deallocates all of the above.
Definition: type_caster_base.h:433
arg
Definition: cast.h:1419
pybind11_getbuffer
int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags)
buffer_protocol: Fill in the view as specified by flags.
Definition: class.h:579
pybind11_meta_getattro
PyObject * pybind11_meta_getattro(PyObject *obj, PyObject *name)
Definition: class.h:175
error_string
std::string error_string()
Definition: pytypes.h:729
info
else if n * info
Definition: 3rdparty/Eigen/lapack/cholesky.cpp:18
get_type_info
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
Definition: type_caster_base.h:193
instance::has_patients
bool has_patients
If true, get_internals().patients has an entry for this object.
Definition: wrap/pybind11/include/pybind11/detail/common.h:642
instance::owned
bool owned
If true, the pointer is owned which means we're free to manage it with a holder.
Definition: wrap/pybind11/include/pybind11/detail/common.h:612
PYBIND11_NAMESPACE
Definition: test_custom_type_casters.cpp:24
pybind11_clear
int pybind11_clear(PyObject *self)
dynamic_attr: Allow the GC to clear the dictionary.
Definition: class.h:549
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1045
make_default_metaclass
PyTypeObject * make_default_metaclass()
Definition: class.h:251
pybind11_object_dealloc
void pybind11_object_dealloc(PyObject *self)
Definition: class.h:457
set_error
void set_error(const handle &type, const char *message)
Definition: pytypes.h:346
register_instance_impl
bool register_instance_impl(void *ptr, instance *self)
Definition: class.h:315
tree::f
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Definition: testExpression.cpp:218
pybind11_releasebuffer
void pybind11_releasebuffer(PyObject *, Py_buffer *view)
buffer_protocol: Release the resources of the buffer.
Definition: class.h:637
type_record::is_final
bool is_final
Is the class inheritable from python classes?
Definition: attr.h:332
internals::direct_conversions
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:193
pybind11_meta_setattro
int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value)
Definition: class.h:138
enable_buffer_protocol
void enable_buffer_protocol(PyHeapTypeObject *heap_type)
Give this type a buffer interface.
Definition: class.h:642
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:250
internals::patients
std::unordered_map< const PyObject *, std::vector< PyObject * > > patients
Definition: internals.h:194
module_
Wrapper for Python extension modules.
Definition: pybind11.h:1171
with_internals
auto with_internals(const F &cb) -> decltype(cb(get_internals()))
Definition: internals.h:640
args
Definition: pytypes.h:2212
buffer_info
Information record describing a Python buffer object.
Definition: buffer_info.h:46
c_str
const char * c_str(Args &&...args)
Definition: internals.h:701
get_local_internals
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:623
instance::weakrefs
PyObject * weakrefs
Weak references.
Definition: wrap/pybind11/include/pybind11/detail/common.h:610
tuple
Definition: pytypes.h:2079
options::show_user_defined_docstrings
static bool show_user_defined_docstrings()
Definition: options.h:62
make_new_python_type
PyObject * make_new_python_type(const type_record &rec)
Definition: class.h:651
clear_instance
void clear_instance(PyObject *self)
Definition: class.h:418
type_record::scope
handle scope
Handle to the parent scope.
Definition: attr.h:278
internals::default_metaclass
PyTypeObject * default_metaclass
Definition: internals.h:204
internals::registered_types_py
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:184
type_record::buffer_protocol
bool buffer_protocol
Does the class implement the buffer protocol?
Definition: attr.h:323
pybind11_static_get
PyObject * pybind11_static_get(PyObject *self, PyObject *, PyObject *cls)
pybind11_static_property.__get__(): Always pass the class instead of the instance.
Definition: class.h:50
pos
Definition: example-NearestNeighbor.cpp:32
type_info::simple_ancestors
bool simple_ancestors
Definition: internals.h:260
pybind11_traverse
int pybind11_traverse(PyObject *self, visitproc visit, void *arg)
dynamic_attr: Allow the garbage collector to traverse the internal instance __dict__.
Definition: class.h:534
PYBIND11_BUILTINS_MODULE
#define PYBIND11_BUILTINS_MODULE
Definition: wrap/pybind11/include/pybind11/detail/common.h:377
values_and_holders
Definition: type_caster_base.h:268
gtsam.examples.ShonanAveragingCLI.str
str
Definition: ShonanAveragingCLI.py:115
pybind11_meta_call
PyObject * pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs)
metaclass __call__ function that is used to create all pybind11 objects.
Definition: class.h:185
type_incref
PyTypeObject * type_incref(PyTypeObject *type)
Definition: class.h:42
test_callbacks.value
value
Definition: test_callbacks.py:162
type_info::get_buffer
buffer_info *(* get_buffer)(PyObject *, void *)
Definition: internals.h:251
register_instance
void register_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:332
pybind_wrapper_test_script.inst
inst
Definition: pybind_wrapper_test_script.py:49
type_record::custom_type_setup_callback
custom_type_setup::callback custom_type_setup_callback
Custom type setup.
Definition: attr.h:314
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:6


gtsam
Author(s):
autogenerated on Wed Mar 19 2025 03:01:23