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 "../attr.h"
13 #include "../options.h"
14 
17 
18 #if !defined(PYPY_VERSION)
19 # define PYBIND11_BUILTIN_QUALNAME
20 # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
21 #else
22 // In PyPy, we still set __qualname__ so that we can produce reliable function type
23 // signatures; in CPython this macro expands to nothing:
24 # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \
25  setattr((PyObject *) obj, "__qualname__", nameobj)
26 #endif
27 
28 inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
29 #if !defined(PYPY_VERSION)
30  return type->tp_name;
31 #else
32  auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
34  return type->tp_name;
35  else
36  return std::move(module_name) + "." + type->tp_name;
37 #endif
38 }
39 
40 inline PyTypeObject *type_incref(PyTypeObject *type) {
41  Py_INCREF(type);
42  return type;
43 }
44 
45 #if !defined(PYPY_VERSION)
46 
48 extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
49  return PyProperty_Type.tp_descr_get(self, cls, cls);
50 }
51 
53 extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
54  PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
55  return PyProperty_Type.tp_descr_set(self, cls, value);
56 }
57 
58 // Forward declaration to use in `make_static_property_type()`
59 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
60 
64 inline PyTypeObject *make_static_property_type() {
65  constexpr auto *name = "pybind11_static_property";
66  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
67 
68  /* Danger zone: from now (and until PyType_Ready), make sure to
69  issue no Python C API calls which could potentially invoke the
70  garbage collector (the GC will call type_traverse(), which will in
71  turn find the newly constructed type in an invalid state) */
72  auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
73  if (!heap_type) {
74  pybind11_fail("make_static_property_type(): error allocating type!");
75  }
76 
77  heap_type->ht_name = name_obj.inc_ref().ptr();
78 # ifdef PYBIND11_BUILTIN_QUALNAME
79  heap_type->ht_qualname = name_obj.inc_ref().ptr();
80 # endif
81 
82  auto *type = &heap_type->ht_type;
83  type->tp_name = name;
84  type->tp_base = type_incref(&PyProperty_Type);
85  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
86  type->tp_descr_get = pybind11_static_get;
87  type->tp_descr_set = pybind11_static_set;
88 
89 # if PY_VERSION_HEX >= 0x030C0000
90  // Since Python-3.12 property-derived types are required to
91  // have dynamic attributes (to set `__doc__`)
92  enable_dynamic_attributes(heap_type);
93 # endif
94 
95  if (PyType_Ready(type) < 0) {
96  pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
97  }
98 
99  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
101 
102  return type;
103 }
104 
105 #else // PYPY
106 
110 inline PyTypeObject *make_static_property_type() {
111  auto d = dict();
112  PyObject *result = PyRun_String(R"(\
113 class pybind11_static_property(property):
114  def __get__(self, obj, cls):
115  return property.__get__(self, cls, cls)
116 
117  def __set__(self, obj, value):
118  cls = obj if isinstance(obj, type) else type(obj)
119  property.__set__(self, cls, value)
120 )",
121  Py_file_input,
122  d.ptr(),
123  d.ptr());
124  if (result == nullptr)
125  throw error_already_set();
126  Py_DECREF(result);
127  return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
128 }
129 
130 #endif // PYPY
131 
136 extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
137  // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
138  // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
139  PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
140 
141  // The following assignment combinations are possible:
142  // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
143  // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
144  // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
145  auto *const static_prop = (PyObject *) get_internals().static_property_type;
146  const auto call_descr_set = (descr != nullptr) && (value != nullptr)
147  && (PyObject_IsInstance(descr, static_prop) != 0)
148  && (PyObject_IsInstance(value, static_prop) == 0);
149  if (call_descr_set) {
150  // Call `static_property.__set__()` instead of replacing the `static_property`.
151 #if !defined(PYPY_VERSION)
152  return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
153 #else
154  if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
155  Py_DECREF(result);
156  return 0;
157  } else {
158  return -1;
159  }
160 #endif
161  } else {
162  // Replace existing attribute.
163  return PyType_Type.tp_setattro(obj, name, value);
164  }
165 }
166 
173 extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
174  PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
175  if (descr && PyInstanceMethod_Check(descr)) {
176  Py_INCREF(descr);
177  return descr;
178  }
179  return PyType_Type.tp_getattro(obj, name);
180 }
181 
183 extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
184 
185  // use the default metaclass call to create/initialize the object
186  PyObject *self = PyType_Type.tp_call(type, args, kwargs);
187  if (self == nullptr) {
188  return nullptr;
189  }
190 
191  // Ensure that the base __init__ function(s) were called
192  values_and_holders vhs(self);
193  for (const auto &vh : vhs) {
194  if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) {
195  PyErr_Format(PyExc_TypeError,
196  "%.200s.__init__() must be called when overriding __init__",
197  get_fully_qualified_tp_name(vh.type->type).c_str());
198  Py_DECREF(self);
199  return nullptr;
200  }
201  }
202 
203  return self;
204 }
205 
207 extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
209  auto *type = (PyTypeObject *) obj;
210 
211  // A pybind11-registered type will:
212  // 1) be found in internals.registered_types_py
213  // 2) have exactly one associated `detail::type_info`
214  auto found_type = internals.registered_types_py.find(type);
215  if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
216  && found_type->second[0]->type == type) {
217 
218  auto *tinfo = found_type->second[0];
219  auto tindex = std::type_index(*tinfo->cpptype);
220  internals.direct_conversions.erase(tindex);
221 
222  if (tinfo->module_local) {
224  } else {
225  internals.registered_types_cpp.erase(tindex);
226  }
227  internals.registered_types_py.erase(tinfo->type);
228 
229  // Actually just `std::erase_if`, but that's only available in C++20
230  auto &cache = internals.inactive_override_cache;
231  for (auto it = cache.begin(), last = cache.end(); it != last;) {
232  if (it->first == (PyObject *) tinfo->type) {
233  it = cache.erase(it);
234  } else {
235  ++it;
236  }
237  }
238 
239  delete tinfo;
240  }
241  });
242 
243  PyType_Type.tp_dealloc(obj);
244 }
245 
249 inline PyTypeObject *make_default_metaclass() {
250  constexpr auto *name = "pybind11_type";
251  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
252 
253  /* Danger zone: from now (and until PyType_Ready), make sure to
254  issue no Python C API calls which could potentially invoke the
255  garbage collector (the GC will call type_traverse(), which will in
256  turn find the newly constructed type in an invalid state) */
257  auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
258  if (!heap_type) {
259  pybind11_fail("make_default_metaclass(): error allocating metaclass!");
260  }
261 
262  heap_type->ht_name = name_obj.inc_ref().ptr();
263 #ifdef PYBIND11_BUILTIN_QUALNAME
264  heap_type->ht_qualname = name_obj.inc_ref().ptr();
265 #endif
266 
267  auto *type = &heap_type->ht_type;
268  type->tp_name = name;
269  type->tp_base = type_incref(&PyType_Type);
270  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
271 
272  type->tp_call = pybind11_meta_call;
273 
274  type->tp_setattro = pybind11_meta_setattro;
275  type->tp_getattro = pybind11_meta_getattro;
276 
277  type->tp_dealloc = pybind11_meta_dealloc;
278 
279  if (PyType_Ready(type) < 0) {
280  pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
281  }
282 
283  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
285 
286  return type;
287 }
288 
293 inline void traverse_offset_bases(void *valueptr,
294  const detail::type_info *tinfo,
295  instance *self,
296  bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
297  for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
298  if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
299  for (auto &c : parent_tinfo->implicit_casts) {
300  if (c.first == tinfo->cpptype) {
301  auto *parentptr = c.second(valueptr);
302  if (parentptr != valueptr) {
303  f(parentptr, self);
304  }
305  traverse_offset_bases(parentptr, parent_tinfo, self, f);
306  break;
307  }
308  }
309  }
310  }
311 }
312 
313 inline bool register_instance_impl(void *ptr, instance *self) {
314  with_instance_map(ptr, [&](instance_map &instances) { instances.emplace(ptr, self); });
315  return true; // unused, but gives the same signature as the deregister func
316 }
317 inline bool deregister_instance_impl(void *ptr, instance *self) {
318  return with_instance_map(ptr, [&](instance_map &instances) {
319  auto range = instances.equal_range(ptr);
320  for (auto it = range.first; it != range.second; ++it) {
321  if (self == it->second) {
322  instances.erase(it);
323  return true;
324  }
325  }
326  return false;
327  });
328 }
329 
330 inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
331  register_instance_impl(valptr, self);
332  if (!tinfo->simple_ancestors) {
333  traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
334  }
335 }
336 
337 inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
338  bool ret = deregister_instance_impl(valptr, self);
339  if (!tinfo->simple_ancestors) {
340  traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
341  }
342  return ret;
343 }
344 
348 inline PyObject *make_new_instance(PyTypeObject *type) {
349 #if defined(PYPY_VERSION)
350  // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
351  // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
352  ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
353  if (type->tp_basicsize < instance_size) {
354  type->tp_basicsize = instance_size;
355  }
356 #endif
357  PyObject *self = type->tp_alloc(type, 0);
358  auto *inst = reinterpret_cast<instance *>(self);
359  // Allocate the value/holder internals:
360  inst->allocate_layout();
361 
362  return self;
363 }
364 
367 extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
368  return make_new_instance(type);
369 }
370 
374 extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
375  PyTypeObject *type = Py_TYPE(self);
376  std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
377  set_error(PyExc_TypeError, msg.c_str());
378  return -1;
379 }
380 
381 inline void add_patient(PyObject *nurse, PyObject *patient) {
382  auto *instance = reinterpret_cast<detail::instance *>(nurse);
383  instance->has_patients = true;
384  Py_INCREF(patient);
385 
386  with_internals([&](internals &internals) { internals.patients[nurse].push_back(patient); });
387 }
388 
389 inline void clear_patients(PyObject *self) {
390  auto *instance = reinterpret_cast<detail::instance *>(self);
391  std::vector<PyObject *> patients;
392 
394  auto pos = internals.patients.find(self);
395 
396  if (pos == internals.patients.end()) {
397  pybind11_fail(
398  "FATAL: Internal consistency check failed: Invalid clear_patients() call.");
399  }
400 
401  // Clearing the patients can cause more Python code to run, which
402  // can invalidate the iterator. Extract the vector of patients
403  // from the unordered_map first.
404  patients = std::move(pos->second);
405  internals.patients.erase(pos);
406  });
407 
408  instance->has_patients = false;
409  for (PyObject *&patient : patients) {
410  Py_CLEAR(patient);
411  }
412 }
413 
416 inline void clear_instance(PyObject *self) {
417  auto *instance = reinterpret_cast<detail::instance *>(self);
418 
419  // Deallocate any values/holders, if present:
420  for (auto &v_h : values_and_holders(instance)) {
421  if (v_h) {
422 
423  // We have to deregister before we call dealloc because, for virtual MI types, we still
424  // need to be able to get the parent pointers.
425  if (v_h.instance_registered()
426  && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
428  "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
429  }
430 
431  if (instance->owned || v_h.holder_constructed()) {
432  v_h.type->dealloc(v_h);
433  }
434  }
435  }
436  // Deallocate the value/holder layout internals:
438 
439  if (instance->weakrefs) {
440  PyObject_ClearWeakRefs(self);
441  }
442 
443  PyObject **dict_ptr = _PyObject_GetDictPtr(self);
444  if (dict_ptr) {
445  Py_CLEAR(*dict_ptr);
446  }
447 
448  if (instance->has_patients) {
449  clear_patients(self);
450  }
451 }
452 
455 extern "C" inline void pybind11_object_dealloc(PyObject *self) {
456  auto *type = Py_TYPE(self);
457 
458  // If this is a GC tracked object, untrack it first
459  // Note that the track call is implicitly done by the
460  // default tp_alloc, which we never override.
461  if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
462  PyObject_GC_UnTrack(self);
463  }
464 
465  clear_instance(self);
466 
467  type->tp_free(self);
468 
469 #if PY_VERSION_HEX < 0x03080000
470  // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
471  // as part of a derived type's dealloc, in which case we're not allowed to decref
472  // the type here. For cross-module compatibility, we shouldn't compare directly
473  // with `pybind11_object_dealloc`, but with the common one stashed in internals.
474  auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
475  if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
476  Py_DECREF(type);
477 #else
478  // This was not needed before Python 3.8 (Python issue 35810)
479  // https://github.com/pybind/pybind11/issues/1946
480  Py_DECREF(type);
481 #endif
482 }
483 
484 std::string error_string();
485 
489 inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
490  constexpr auto *name = "pybind11_object";
491  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
492 
493  /* Danger zone: from now (and until PyType_Ready), make sure to
494  issue no Python C API calls which could potentially invoke the
495  garbage collector (the GC will call type_traverse(), which will in
496  turn find the newly constructed type in an invalid state) */
497  auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
498  if (!heap_type) {
499  pybind11_fail("make_object_base_type(): error allocating type!");
500  }
501 
502  heap_type->ht_name = name_obj.inc_ref().ptr();
503 #ifdef PYBIND11_BUILTIN_QUALNAME
504  heap_type->ht_qualname = name_obj.inc_ref().ptr();
505 #endif
506 
507  auto *type = &heap_type->ht_type;
508  type->tp_name = name;
509  type->tp_base = type_incref(&PyBaseObject_Type);
510  type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
511  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
512 
513  type->tp_new = pybind11_object_new;
514  type->tp_init = pybind11_object_init;
515  type->tp_dealloc = pybind11_object_dealloc;
516 
517  /* Support weak references (needed for the keep_alive feature) */
518  type->tp_weaklistoffset = offsetof(instance, weakrefs);
519 
520  if (PyType_Ready(type) < 0) {
521  pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
522  }
523 
524  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
526 
527  assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
528  return (PyObject *) heap_type;
529 }
530 
532 extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
533 #if PY_VERSION_HEX >= 0x030D0000
534  PyObject_VisitManagedDict(self, visit, arg);
535 #else
536  PyObject *&dict = *_PyObject_GetDictPtr(self);
537  Py_VISIT(dict);
538 #endif
539 // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
540 #if PY_VERSION_HEX >= 0x03090000
541  Py_VISIT(Py_TYPE(self));
542 #endif
543  return 0;
544 }
545 
547 extern "C" inline int pybind11_clear(PyObject *self) {
548 #if PY_VERSION_HEX >= 0x030D0000
549  PyObject_ClearManagedDict(self);
550 #else
551  PyObject *&dict = *_PyObject_GetDictPtr(self);
552  Py_CLEAR(dict);
553 #endif
554  return 0;
555 }
556 
558 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
559  auto *type = &heap_type->ht_type;
560  type->tp_flags |= Py_TPFLAGS_HAVE_GC;
561 #if PY_VERSION_HEX < 0x030B0000
562  type->tp_dictoffset = type->tp_basicsize; // place dict at the end
563  type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
564 #else
565  type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
566 #endif
567  type->tp_traverse = pybind11_traverse;
568  type->tp_clear = pybind11_clear;
569 
570  static PyGetSetDef getset[]
571  = {{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, nullptr, nullptr},
572  {nullptr, nullptr, nullptr, nullptr, nullptr}};
573  type->tp_getset = getset;
574 }
575 
577 extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
578  // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
579  type_info *tinfo = nullptr;
580  for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
581  tinfo = get_type_info((PyTypeObject *) type.ptr());
582  if (tinfo && tinfo->get_buffer) {
583  break;
584  }
585  }
586  if (view == nullptr || !tinfo || !tinfo->get_buffer) {
587  if (view) {
588  view->obj = nullptr;
589  }
590  set_error(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
591  return -1;
592  }
593  std::memset(view, 0, sizeof(Py_buffer));
594  buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
595  if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
596  delete info;
597  // view->obj = nullptr; // Was just memset to 0, so not necessary
598  set_error(PyExc_BufferError, "Writable buffer requested for readonly storage");
599  return -1;
600  }
601  view->obj = obj;
602  view->ndim = 1;
603  view->internal = info;
604  view->buf = info->ptr;
605  view->itemsize = info->itemsize;
606  view->len = view->itemsize;
607  for (auto s : info->shape) {
608  view->len *= s;
609  }
610  view->readonly = static_cast<int>(info->readonly);
611  if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
612  view->format = const_cast<char *>(info->format.c_str());
613  }
614  if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
615  view->ndim = (int) info->ndim;
616  view->strides = info->strides.data();
617  view->shape = info->shape.data();
618  }
619  Py_INCREF(view->obj);
620  return 0;
621 }
622 
624 extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
625  delete (buffer_info *) view->internal;
626 }
627 
629 inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
630  heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
631 
632  heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
633  heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
634 }
635 
638 inline PyObject *make_new_python_type(const type_record &rec) {
639  auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
640 
641  auto qualname = name;
642  if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
643  qualname = reinterpret_steal<object>(
644  PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
645  }
646 
647  object module_;
648  if (rec.scope) {
649  if (hasattr(rec.scope, "__module__")) {
650  module_ = rec.scope.attr("__module__");
651  } else if (hasattr(rec.scope, "__name__")) {
652  module_ = rec.scope.attr("__name__");
653  }
654  }
655 
656  const auto *full_name = c_str(
657 #if !defined(PYPY_VERSION)
658  module_ ? str(module_).cast<std::string>() + "." + rec.name :
659 #endif
660  rec.name);
661 
662  char *tp_doc = nullptr;
664  /* Allocate memory for docstring (Python will free this later on) */
665  size_t size = std::strlen(rec.doc) + 1;
666 #if PY_VERSION_HEX >= 0x030D0000
667  tp_doc = (char *) PyMem_MALLOC(size);
668 #else
669  tp_doc = (char *) PyObject_MALLOC(size);
670 #endif
671  std::memcpy((void *) tp_doc, rec.doc, size);
672  }
673 
674  auto &internals = get_internals();
675  auto bases = tuple(rec.bases);
676  auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
677 
678  /* Danger zone: from now (and until PyType_Ready), make sure to
679  issue no Python C API calls which could potentially invoke the
680  garbage collector (the GC will call type_traverse(), which will in
681  turn find the newly constructed type in an invalid state) */
682  auto *metaclass
683  = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
684 
685  auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
686  if (!heap_type) {
687  pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
688  }
689 
690  heap_type->ht_name = name.release().ptr();
691 #ifdef PYBIND11_BUILTIN_QUALNAME
692  heap_type->ht_qualname = qualname.inc_ref().ptr();
693 #endif
694 
695  auto *type = &heap_type->ht_type;
696  type->tp_name = full_name;
697  type->tp_doc = tp_doc;
698  type->tp_base = type_incref((PyTypeObject *) base);
699  type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
700  if (!bases.empty()) {
701  type->tp_bases = bases.release().ptr();
702  }
703 
704  /* Don't inherit base __init__ */
705  type->tp_init = pybind11_object_init;
706 
707  /* Supported protocols */
708  type->tp_as_number = &heap_type->as_number;
709  type->tp_as_sequence = &heap_type->as_sequence;
710  type->tp_as_mapping = &heap_type->as_mapping;
711  type->tp_as_async = &heap_type->as_async;
712 
713  /* Flags */
714  type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
715  if (!rec.is_final) {
716  type->tp_flags |= Py_TPFLAGS_BASETYPE;
717  }
718 
719  if (rec.dynamic_attr) {
720  enable_dynamic_attributes(heap_type);
721  }
722 
723  if (rec.buffer_protocol) {
724  enable_buffer_protocol(heap_type);
725  }
726 
727  if (rec.custom_type_setup_callback) {
728  rec.custom_type_setup_callback(heap_type);
729  }
730 
731  if (PyType_Ready(type) < 0) {
732  pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
733  }
734 
735  assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
736 
737  /* Register type with the parent scope */
738  if (rec.scope) {
739  setattr(rec.scope, rec.name, (PyObject *) type);
740  } else {
741  Py_INCREF(type); // Keep it alive forever (reference leak)
742  }
743 
744  if (module_) { // Needed by pydoc
745  setattr((PyObject *) type, "__module__", module_);
746  }
747 
749 
750  return (PyObject *) type;
751 }
752 
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:337
name
Annotation for function names.
Definition: attr.h:51
pybind11_object_init
int pybind11_object_init(PyObject *self, PyObject *, PyObject *)
Definition: class.h:374
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:53
internals
Definition: internals.h:162
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:639
clear_patients
void clear_patients(PyObject *self)
Definition: class.h:389
add_patient
void add_patient(PyObject *nurse, PyObject *patient)
Definition: class.h:381
traverse_offset_bases
void traverse_offset_bases(void *valueptr, const detail::type_info *tinfo, instance *self, bool(*f)(void *, instance *))
Definition: class.h:293
gtsam.examples.DogLegOptimizerExample.type
type
Definition: DogLegOptimizerExample.py:111
ssize_t
Py_ssize_t ssize_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:489
error_already_set
Definition: pytypes.h:739
type_info
Definition: internals.h:226
kwargs
Definition: pytypes.h:2213
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:167
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
type_info::get_buffer_data
void * get_buffer_data
Definition: internals.h:237
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:1525
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:558
detail
Definition: testSerializationNonlinear.cpp:70
internals::static_property_type
PyTypeObject * static_property_type
Definition: internals.h:188
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:483
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:64
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:348
deregister_instance_impl
bool deregister_instance_impl(void *ptr, instance *self)
Definition: class.h:317
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:489
internals::instance_base
PyObject * instance_base
Definition: internals.h:190
PYBIND11_SET_OLDPY_QUALNAME
#define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
Definition: class.h:20
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:583
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:2107
get_fully_qualified_tp_name
std::string get_fully_qualified_tp_name(PyTypeObject *type)
Definition: class.h:28
pybind11_meta_dealloc
void pybind11_meta_dealloc(PyObject *obj)
Cleanup the type-info for a pybind11-registered type.
Definition: class.h:207
handle
Definition: pytypes.h:226
handle::cast
T cast() const
Definition: cast.h:1234
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:177
pybind11_object_new
PyObject * pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *)
Definition: class.h:367
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:567
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:489
arg
Definition: cast.h:1412
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:577
pybind11_meta_getattro
PyObject * pybind11_meta_getattro(PyObject *obj, PyObject *name)
Definition: class.h:173
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:188
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:623
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:593
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:547
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1026
make_default_metaclass
PyTypeObject * make_default_metaclass()
Definition: class.h:249
pybind11_object_dealloc
void pybind11_object_dealloc(PyObject *self)
Definition: class.h:455
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:313
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:624
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:178
pybind11_meta_setattro
int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value)
Definition: class.h:136
enable_buffer_protocol
void enable_buffer_protocol(PyHeapTypeObject *heap_type)
Give this type a buffer interface.
Definition: class.h:629
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:179
module_
Wrapper for Python extension modules.
Definition: pybind11.h:1220
with_internals
auto with_internals(const F &cb) -> decltype(cb(get_internals()))
Definition: internals.h:623
args
Definition: pytypes.h:2210
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:684
get_local_internals
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:606
instance::weakrefs
PyObject * weakrefs
Weak references.
Definition: wrap/pybind11/include/pybind11/detail/common.h:591
tuple
Definition: pytypes.h:2077
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:638
clear_instance
void clear_instance(PyObject *self)
Definition: class.h:416
type_record::scope
handle scope
Handle to the parent scope.
Definition: attr.h:278
internals::default_metaclass
PyTypeObject * default_metaclass
Definition: internals.h:189
internals::registered_types_py
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:169
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:48
pos
Definition: example-NearestNeighbor.cpp:32
type_info::simple_ancestors
bool simple_ancestors
Definition: internals.h:245
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:532
PYBIND11_BUILTINS_MODULE
#define PYBIND11_BUILTINS_MODULE
Definition: wrap/pybind11/include/pybind11/detail/common.h:377
values_and_holders
Definition: type_caster_base.h:324
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:183
type_incref
PyTypeObject * type_incref(PyTypeObject *type)
Definition: class.h:40
test_callbacks.value
value
Definition: test_callbacks.py:160
type_info::get_buffer
buffer_info *(* get_buffer)(PyObject *, void *)
Definition: internals.h:236
register_instance
void register_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:330
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 Sat Nov 16 2024 04:01:58