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 (PyType_Ready(type) < 0) {
90  pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
91  }
92 
93 # if PY_VERSION_HEX >= 0x030C0000
94  // PRE 3.12 FEATURE FREEZE. PLEASE REVIEW AFTER FREEZE.
95  // Since Python-3.12 property-derived types are required to
96  // have dynamic attributes (to set `__doc__`)
97  enable_dynamic_attributes(heap_type);
98 # endif
99 
100  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
102 
103  return type;
104 }
105 
106 #else // PYPY
107 
111 inline PyTypeObject *make_static_property_type() {
112  auto d = dict();
113  PyObject *result = PyRun_String(R"(\
114 class pybind11_static_property(property):
115  def __get__(self, obj, cls):
116  return property.__get__(self, cls, cls)
117 
118  def __set__(self, obj, value):
119  cls = obj if isinstance(obj, type) else type(obj)
120  property.__set__(self, cls, value)
121 )",
122  Py_file_input,
123  d.ptr(),
124  d.ptr());
125  if (result == nullptr)
126  throw error_already_set();
127  Py_DECREF(result);
128  return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
129 }
130 
131 #endif // PYPY
132 
137 extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
138  // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
139  // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
140  PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
141 
142  // The following assignment combinations are possible:
143  // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
144  // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
145  // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
146  auto *const static_prop = (PyObject *) get_internals().static_property_type;
147  const auto call_descr_set = (descr != nullptr) && (value != nullptr)
148  && (PyObject_IsInstance(descr, static_prop) != 0)
149  && (PyObject_IsInstance(value, static_prop) == 0);
150  if (call_descr_set) {
151  // Call `static_property.__set__()` instead of replacing the `static_property`.
152 #if !defined(PYPY_VERSION)
153  return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
154 #else
155  if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
156  Py_DECREF(result);
157  return 0;
158  } else {
159  return -1;
160  }
161 #endif
162  } else {
163  // Replace existing attribute.
164  return PyType_Type.tp_setattro(obj, name, value);
165  }
166 }
167 
174 extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
175  PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
176  if (descr && PyInstanceMethod_Check(descr)) {
177  Py_INCREF(descr);
178  return descr;
179  }
180  return PyType_Type.tp_getattro(obj, name);
181 }
182 
184 extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
185 
186  // use the default metaclass call to create/initialize the object
187  PyObject *self = PyType_Type.tp_call(type, args, kwargs);
188  if (self == nullptr) {
189  return nullptr;
190  }
191 
192  // This must be a pybind11 instance
193  auto *instance = reinterpret_cast<detail::instance *>(self);
194 
195  // Ensure that the base __init__ function(s) were called
196  for (const auto &vh : values_and_holders(instance)) {
197  if (!vh.holder_constructed()) {
198  PyErr_Format(PyExc_TypeError,
199  "%.200s.__init__() must be called when overriding __init__",
200  get_fully_qualified_tp_name(vh.type->type).c_str());
201  Py_DECREF(self);
202  return nullptr;
203  }
204  }
205 
206  return self;
207 }
208 
210 extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
211  auto *type = (PyTypeObject *) obj;
212  auto &internals = get_internals();
213 
214  // A pybind11-registered type will:
215  // 1) be found in internals.registered_types_py
216  // 2) have exactly one associated `detail::type_info`
217  auto found_type = internals.registered_types_py.find(type);
218  if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
219  && found_type->second[0]->type == type) {
220 
221  auto *tinfo = found_type->second[0];
222  auto tindex = std::type_index(*tinfo->cpptype);
223  internals.direct_conversions.erase(tindex);
224 
225  if (tinfo->module_local) {
227  } else {
228  internals.registered_types_cpp.erase(tindex);
229  }
230  internals.registered_types_py.erase(tinfo->type);
231 
232  // Actually just `std::erase_if`, but that's only available in C++20
233  auto &cache = internals.inactive_override_cache;
234  for (auto it = cache.begin(), last = cache.end(); it != last;) {
235  if (it->first == (PyObject *) tinfo->type) {
236  it = cache.erase(it);
237  } else {
238  ++it;
239  }
240  }
241 
242  delete tinfo;
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  get_internals().registered_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  auto &registered_instances = get_internals().registered_instances;
321  auto range = registered_instances.equal_range(ptr);
322  for (auto it = range.first; it != range.second; ++it) {
323  if (self == it->second) {
324  registered_instances.erase(it);
325  return true;
326  }
327  }
328  return false;
329 }
330 
331 inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
332  register_instance_impl(valptr, self);
333  if (!tinfo->simple_ancestors) {
334  traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
335  }
336 }
337 
338 inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
339  bool ret = deregister_instance_impl(valptr, self);
340  if (!tinfo->simple_ancestors) {
341  traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
342  }
343  return ret;
344 }
345 
349 inline PyObject *make_new_instance(PyTypeObject *type) {
350 #if defined(PYPY_VERSION)
351  // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
352  // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
353  ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
354  if (type->tp_basicsize < instance_size) {
355  type->tp_basicsize = instance_size;
356  }
357 #endif
358  PyObject *self = type->tp_alloc(type, 0);
359  auto *inst = reinterpret_cast<instance *>(self);
360  // Allocate the value/holder internals:
361  inst->allocate_layout();
362 
363  return self;
364 }
365 
368 extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
369  return make_new_instance(type);
370 }
371 
375 extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
376  PyTypeObject *type = Py_TYPE(self);
377  std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
378  PyErr_SetString(PyExc_TypeError, msg.c_str());
379  return -1;
380 }
381 
382 inline void add_patient(PyObject *nurse, PyObject *patient) {
383  auto &internals = get_internals();
384  auto *instance = reinterpret_cast<detail::instance *>(nurse);
385  instance->has_patients = true;
386  Py_INCREF(patient);
387  internals.patients[nurse].push_back(patient);
388 }
389 
390 inline void clear_patients(PyObject *self) {
391  auto *instance = reinterpret_cast<detail::instance *>(self);
392  auto &internals = get_internals();
393  auto pos = internals.patients.find(self);
394  assert(pos != internals.patients.end());
395  // Clearing the patients can cause more Python code to run, which
396  // can invalidate the iterator. Extract the vector of patients
397  // from the unordered_map first.
398  auto patients = std::move(pos->second);
399  internals.patients.erase(pos);
400  instance->has_patients = false;
401  for (PyObject *&patient : patients) {
402  Py_CLEAR(patient);
403  }
404 }
405 
408 inline void clear_instance(PyObject *self) {
409  auto *instance = reinterpret_cast<detail::instance *>(self);
410 
411  // Deallocate any values/holders, if present:
412  for (auto &v_h : values_and_holders(instance)) {
413  if (v_h) {
414 
415  // We have to deregister before we call dealloc because, for virtual MI types, we still
416  // need to be able to get the parent pointers.
417  if (v_h.instance_registered()
418  && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
420  "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
421  }
422 
423  if (instance->owned || v_h.holder_constructed()) {
424  v_h.type->dealloc(v_h);
425  }
426  }
427  }
428  // Deallocate the value/holder layout internals:
430 
431  if (instance->weakrefs) {
432  PyObject_ClearWeakRefs(self);
433  }
434 
435  PyObject **dict_ptr = _PyObject_GetDictPtr(self);
436  if (dict_ptr) {
437  Py_CLEAR(*dict_ptr);
438  }
439 
440  if (instance->has_patients) {
441  clear_patients(self);
442  }
443 }
444 
447 extern "C" inline void pybind11_object_dealloc(PyObject *self) {
448  auto *type = Py_TYPE(self);
449 
450  // If this is a GC tracked object, untrack it first
451  // Note that the track call is implicitly done by the
452  // default tp_alloc, which we never override.
453  if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
454  PyObject_GC_UnTrack(self);
455  }
456 
457  clear_instance(self);
458 
459  type->tp_free(self);
460 
461 #if PY_VERSION_HEX < 0x03080000
462  // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
463  // as part of a derived type's dealloc, in which case we're not allowed to decref
464  // the type here. For cross-module compatibility, we shouldn't compare directly
465  // with `pybind11_object_dealloc`, but with the common one stashed in internals.
466  auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
467  if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
468  Py_DECREF(type);
469 #else
470  // This was not needed before Python 3.8 (Python issue 35810)
471  // https://github.com/pybind/pybind11/issues/1946
472  Py_DECREF(type);
473 #endif
474 }
475 
476 std::string error_string();
477 
481 inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
482  constexpr auto *name = "pybind11_object";
483  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
484 
485  /* Danger zone: from now (and until PyType_Ready), make sure to
486  issue no Python C API calls which could potentially invoke the
487  garbage collector (the GC will call type_traverse(), which will in
488  turn find the newly constructed type in an invalid state) */
489  auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
490  if (!heap_type) {
491  pybind11_fail("make_object_base_type(): error allocating type!");
492  }
493 
494  heap_type->ht_name = name_obj.inc_ref().ptr();
495 #ifdef PYBIND11_BUILTIN_QUALNAME
496  heap_type->ht_qualname = name_obj.inc_ref().ptr();
497 #endif
498 
499  auto *type = &heap_type->ht_type;
500  type->tp_name = name;
501  type->tp_base = type_incref(&PyBaseObject_Type);
502  type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
503  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
504 
505  type->tp_new = pybind11_object_new;
506  type->tp_init = pybind11_object_init;
507  type->tp_dealloc = pybind11_object_dealloc;
508 
509  /* Support weak references (needed for the keep_alive feature) */
510  type->tp_weaklistoffset = offsetof(instance, weakrefs);
511 
512  if (PyType_Ready(type) < 0) {
513  pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
514  }
515 
516  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
518 
519  assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
520  return (PyObject *) heap_type;
521 }
522 
524 extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
525  PyObject *&dict = *_PyObject_GetDictPtr(self);
526  Py_VISIT(dict);
527 // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
528 #if PY_VERSION_HEX >= 0x03090000
529  Py_VISIT(Py_TYPE(self));
530 #endif
531  return 0;
532 }
533 
535 extern "C" inline int pybind11_clear(PyObject *self) {
536  PyObject *&dict = *_PyObject_GetDictPtr(self);
537  Py_CLEAR(dict);
538  return 0;
539 }
540 
542 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
543  auto *type = &heap_type->ht_type;
544  type->tp_flags |= Py_TPFLAGS_HAVE_GC;
545 #if PY_VERSION_HEX < 0x030B0000
546  type->tp_dictoffset = type->tp_basicsize; // place dict at the end
547  type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
548 #else
549  type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
550 #endif
551  type->tp_traverse = pybind11_traverse;
552  type->tp_clear = pybind11_clear;
553 
554  static PyGetSetDef getset[] = {{
555 #if PY_VERSION_HEX < 0x03070000
556  const_cast<char *>("__dict__"),
557 #else
558  "__dict__",
559 #endif
560  PyObject_GenericGetDict,
561  PyObject_GenericSetDict,
562  nullptr,
563  nullptr},
564  {nullptr, nullptr, nullptr, nullptr, nullptr}};
565  type->tp_getset = getset;
566 }
567 
569 extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
570  // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
571  type_info *tinfo = nullptr;
572  for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
573  tinfo = get_type_info((PyTypeObject *) type.ptr());
574  if (tinfo && tinfo->get_buffer) {
575  break;
576  }
577  }
578  if (view == nullptr || !tinfo || !tinfo->get_buffer) {
579  if (view) {
580  view->obj = nullptr;
581  }
582  PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
583  return -1;
584  }
585  std::memset(view, 0, sizeof(Py_buffer));
586  buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
587  if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
588  delete info;
589  // view->obj = nullptr; // Was just memset to 0, so not necessary
590  PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
591  return -1;
592  }
593  view->obj = obj;
594  view->ndim = 1;
595  view->internal = info;
596  view->buf = info->ptr;
597  view->itemsize = info->itemsize;
598  view->len = view->itemsize;
599  for (auto s : info->shape) {
600  view->len *= s;
601  }
602  view->readonly = static_cast<int>(info->readonly);
603  if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
604  view->format = const_cast<char *>(info->format.c_str());
605  }
606  if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
607  view->ndim = (int) info->ndim;
608  view->strides = info->strides.data();
609  view->shape = info->shape.data();
610  }
611  Py_INCREF(view->obj);
612  return 0;
613 }
614 
616 extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
617  delete (buffer_info *) view->internal;
618 }
619 
621 inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
622  heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
623 
624  heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
625  heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
626 }
627 
630 inline PyObject *make_new_python_type(const type_record &rec) {
631  auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
632 
633  auto qualname = name;
634  if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
635  qualname = reinterpret_steal<object>(
636  PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
637  }
638 
639  object module_;
640  if (rec.scope) {
641  if (hasattr(rec.scope, "__module__")) {
642  module_ = rec.scope.attr("__module__");
643  } else if (hasattr(rec.scope, "__name__")) {
644  module_ = rec.scope.attr("__name__");
645  }
646  }
647 
648  const auto *full_name = c_str(
649 #if !defined(PYPY_VERSION)
650  module_ ? str(module_).cast<std::string>() + "." + rec.name :
651 #endif
652  rec.name);
653 
654  char *tp_doc = nullptr;
656  /* Allocate memory for docstring (using PyObject_MALLOC, since
657  Python will free this later on) */
658  size_t size = std::strlen(rec.doc) + 1;
659  tp_doc = (char *) PyObject_MALLOC(size);
660  std::memcpy((void *) tp_doc, rec.doc, size);
661  }
662 
663  auto &internals = get_internals();
664  auto bases = tuple(rec.bases);
665  auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
666 
667  /* Danger zone: from now (and until PyType_Ready), make sure to
668  issue no Python C API calls which could potentially invoke the
669  garbage collector (the GC will call type_traverse(), which will in
670  turn find the newly constructed type in an invalid state) */
671  auto *metaclass
672  = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
673 
674  auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
675  if (!heap_type) {
676  pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
677  }
678 
679  heap_type->ht_name = name.release().ptr();
680 #ifdef PYBIND11_BUILTIN_QUALNAME
681  heap_type->ht_qualname = qualname.inc_ref().ptr();
682 #endif
683 
684  auto *type = &heap_type->ht_type;
685  type->tp_name = full_name;
686  type->tp_doc = tp_doc;
687  type->tp_base = type_incref((PyTypeObject *) base);
688  type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
689  if (!bases.empty()) {
690  type->tp_bases = bases.release().ptr();
691  }
692 
693  /* Don't inherit base __init__ */
694  type->tp_init = pybind11_object_init;
695 
696  /* Supported protocols */
697  type->tp_as_number = &heap_type->as_number;
698  type->tp_as_sequence = &heap_type->as_sequence;
699  type->tp_as_mapping = &heap_type->as_mapping;
700  type->tp_as_async = &heap_type->as_async;
701 
702  /* Flags */
703  type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
704  if (!rec.is_final) {
705  type->tp_flags |= Py_TPFLAGS_BASETYPE;
706  }
707 
708  if (rec.dynamic_attr) {
709  enable_dynamic_attributes(heap_type);
710  }
711 
712  if (rec.buffer_protocol) {
713  enable_buffer_protocol(heap_type);
714  }
715 
716  if (rec.custom_type_setup_callback) {
717  rec.custom_type_setup_callback(heap_type);
718  }
719 
720  if (PyType_Ready(type) < 0) {
721  pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
722  }
723 
724  assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
725 
726  /* Register type with the parent scope */
727  if (rec.scope) {
728  setattr(rec.scope, rec.name, (PyObject *) type);
729  } else {
730  Py_INCREF(type); // Keep it alive forever (reference leak)
731  }
732 
733  if (module_) { // Needed by pydoc
734  setattr((PyObject *) type, "__module__", module_);
735  }
736 
738 
739  return (PyObject *) type;
740 }
741 
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:338
name
Annotation for function names.
Definition: attr.h:51
pybind11_object_init
int pybind11_object_init(PyObject *self, PyObject *, PyObject *)
Definition: class.h:375
setattr
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:905
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:168
base
Annotation indicating that a class derives from another given type.
Definition: attr.h:64
clear_patients
void clear_patients(PyObject *self)
Definition: class.h:390
add_patient
void add_patient(PyObject *nurse, PyObject *patient)
Definition: class.h:382
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:475
error_already_set
Definition: pytypes.h:722
type_info
Definition: internals.h:226
kwargs
Definition: pytypes.h:2166
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:170
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:853
type
Definition: pytypes.h:1491
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:542
detail
Definition: testSerializationNonlinear.cpp:70
internals::static_property_type
PyTypeObject * static_property_type
Definition: internals.h:186
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:467
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:362
make_new_instance
PyObject * make_new_instance(PyTypeObject *type)
Definition: class.h:349
deregister_instance_impl
bool deregister_instance_impl(void *ptr, instance *self)
Definition: class.h:319
name
static char name[]
Definition: rgamma.c:72
internals::registered_instances
std::unordered_multimap< const void *, instance * > registered_instances
Definition: internals.h:173
size
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
make_object_base_type
PyObject * make_object_base_type(PyTypeObject *metaclass)
Definition: class.h:481
internals::instance_base
PyObject * instance_base
Definition: internals.h:188
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:569
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:2065
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:210
handle
Definition: pytypes.h:217
handle::cast
T cast() const
Definition: cast.h:1110
conf.release
release
Definition: gtsam/3rdparty/GeographicLib/python/doc/conf.py:69
internals::inactive_override_cache
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:175
pybind11_object_new
PyObject * pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *)
Definition: class.h:368
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:368
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:545
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:459
arg
Definition: cast.h:1277
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:569
pybind11_meta_getattro
PyObject * pybind11_meta_getattro(PyObject *obj, PyObject *name)
Definition: class.h:174
error_string
std::string error_string()
Definition: pytypes.h:712
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:184
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:609
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:579
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:535
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1013
make_default_metaclass
PyTypeObject * make_default_metaclass()
Definition: class.h:251
pybind11_object_dealloc
void pybind11_object_dealloc(PyObject *self)
Definition: class.h:447
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:616
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:176
pybind11_meta_setattro
int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value)
Definition: class.h:137
enable_buffer_protocol
void enable_buffer_protocol(PyHeapTypeObject *heap_type)
Give this type a buffer interface.
Definition: class.h:621
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:241
internals::patients
std::unordered_map< const PyObject *, std::vector< PyObject * > > patients
Definition: internals.h:177
module_
Wrapper for Python extension modules.
Definition: pybind11.h:1153
args
Definition: pytypes.h:2163
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:599
get_local_internals
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:584
instance::weakrefs
PyObject * weakrefs
Weak references.
Definition: wrap/pybind11/include/pybind11/detail/common.h:577
tuple
Definition: pytypes.h:2035
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:630
clear_instance
void clear_instance(PyObject *self)
Definition: class.h:408
type_record::scope
handle scope
Handle to the parent scope.
Definition: attr.h:278
internals::default_metaclass
PyTypeObject * default_metaclass
Definition: internals.h:187
internals::registered_types_py
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:172
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:524
PYBIND11_BUILTINS_MODULE
#define PYBIND11_BUILTINS_MODULE
Definition: wrap/pybind11/include/pybind11/detail/common.h:366
values_and_holders
Definition: type_caster_base.h:315
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:184
type_incref
PyTypeObject * type_incref(PyTypeObject *type)
Definition: class.h:40
test_callbacks.value
value
Definition: test_callbacks.py:158
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:331
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:4


gtsam
Author(s):
autogenerated on Thu Jun 13 2024 03:01:53