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 
61 inline PyTypeObject *make_static_property_type() {
62  constexpr auto *name = "pybind11_static_property";
63  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
64 
65  /* Danger zone: from now (and until PyType_Ready), make sure to
66  issue no Python C API calls which could potentially invoke the
67  garbage collector (the GC will call type_traverse(), which will in
68  turn find the newly constructed type in an invalid state) */
69  auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
70  if (!heap_type) {
71  pybind11_fail("make_static_property_type(): error allocating type!");
72  }
73 
74  heap_type->ht_name = name_obj.inc_ref().ptr();
75 # ifdef PYBIND11_BUILTIN_QUALNAME
76  heap_type->ht_qualname = name_obj.inc_ref().ptr();
77 # endif
78 
79  auto *type = &heap_type->ht_type;
80  type->tp_name = name;
81  type->tp_base = type_incref(&PyProperty_Type);
82  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
83  type->tp_descr_get = pybind11_static_get;
84  type->tp_descr_set = pybind11_static_set;
85 
86  if (PyType_Ready(type) < 0) {
87  pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
88  }
89 
90  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
91  PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
92 
93  return type;
94 }
95 
96 #else // PYPY
97 
101 inline PyTypeObject *make_static_property_type() {
102  auto d = dict();
103  PyObject *result = PyRun_String(R"(\
104 class pybind11_static_property(property):
105  def __get__(self, obj, cls):
106  return property.__get__(self, cls, cls)
107 
108  def __set__(self, obj, value):
109  cls = obj if isinstance(obj, type) else type(obj)
110  property.__set__(self, cls, value)
111 )",
112  Py_file_input,
113  d.ptr(),
114  d.ptr());
115  if (result == nullptr)
116  throw error_already_set();
117  Py_DECREF(result);
118  return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
119 }
120 
121 #endif // PYPY
122 
127 extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
128  // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
129  // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
130  PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
131 
132  // The following assignment combinations are possible:
133  // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
134  // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
135  // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
136  auto *const static_prop = (PyObject *) get_internals().static_property_type;
137  const auto call_descr_set = (descr != nullptr) && (value != nullptr)
138  && (PyObject_IsInstance(descr, static_prop) != 0)
139  && (PyObject_IsInstance(value, static_prop) == 0);
140  if (call_descr_set) {
141  // Call `static_property.__set__()` instead of replacing the `static_property`.
142 #if !defined(PYPY_VERSION)
143  return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
144 #else
145  if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
146  Py_DECREF(result);
147  return 0;
148  } else {
149  return -1;
150  }
151 #endif
152  } else {
153  // Replace existing attribute.
154  return PyType_Type.tp_setattro(obj, name, value);
155  }
156 }
157 
164 extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
165  PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
166  if (descr && PyInstanceMethod_Check(descr)) {
167  Py_INCREF(descr);
168  return descr;
169  }
170  return PyType_Type.tp_getattro(obj, name);
171 }
172 
174 extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
175 
176  // use the default metaclass call to create/initialize the object
177  PyObject *self = PyType_Type.tp_call(type, args, kwargs);
178  if (self == nullptr) {
179  return nullptr;
180  }
181 
182  // This must be a pybind11 instance
183  auto *instance = reinterpret_cast<detail::instance *>(self);
184 
185  // Ensure that the base __init__ function(s) were called
186  for (const auto &vh : values_and_holders(instance)) {
187  if (!vh.holder_constructed()) {
188  PyErr_Format(PyExc_TypeError,
189  "%.200s.__init__() must be called when overriding __init__",
190  get_fully_qualified_tp_name(vh.type->type).c_str());
191  Py_DECREF(self);
192  return nullptr;
193  }
194  }
195 
196  return self;
197 }
198 
200 extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
201  auto *type = (PyTypeObject *) obj;
202  auto &internals = get_internals();
203 
204  // A pybind11-registered type will:
205  // 1) be found in internals.registered_types_py
206  // 2) have exactly one associated `detail::type_info`
207  auto found_type = internals.registered_types_py.find(type);
208  if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
209  && found_type->second[0]->type == type) {
210 
211  auto *tinfo = found_type->second[0];
212  auto tindex = std::type_index(*tinfo->cpptype);
213  internals.direct_conversions.erase(tindex);
214 
215  if (tinfo->module_local) {
217  } else {
218  internals.registered_types_cpp.erase(tindex);
219  }
220  internals.registered_types_py.erase(tinfo->type);
221 
222  // Actually just `std::erase_if`, but that's only available in C++20
223  auto &cache = internals.inactive_override_cache;
224  for (auto it = cache.begin(), last = cache.end(); it != last;) {
225  if (it->first == (PyObject *) tinfo->type) {
226  it = cache.erase(it);
227  } else {
228  ++it;
229  }
230  }
231 
232  delete tinfo;
233  }
234 
235  PyType_Type.tp_dealloc(obj);
236 }
237 
241 inline PyTypeObject *make_default_metaclass() {
242  constexpr auto *name = "pybind11_type";
243  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
244 
245  /* Danger zone: from now (and until PyType_Ready), make sure to
246  issue no Python C API calls which could potentially invoke the
247  garbage collector (the GC will call type_traverse(), which will in
248  turn find the newly constructed type in an invalid state) */
249  auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
250  if (!heap_type) {
251  pybind11_fail("make_default_metaclass(): error allocating metaclass!");
252  }
253 
254  heap_type->ht_name = name_obj.inc_ref().ptr();
255 #ifdef PYBIND11_BUILTIN_QUALNAME
256  heap_type->ht_qualname = name_obj.inc_ref().ptr();
257 #endif
258 
259  auto *type = &heap_type->ht_type;
260  type->tp_name = name;
261  type->tp_base = type_incref(&PyType_Type);
262  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
263 
264  type->tp_call = pybind11_meta_call;
265 
266  type->tp_setattro = pybind11_meta_setattro;
267  type->tp_getattro = pybind11_meta_getattro;
268 
269  type->tp_dealloc = pybind11_meta_dealloc;
270 
271  if (PyType_Ready(type) < 0) {
272  pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
273  }
274 
275  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
276  PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
277 
278  return type;
279 }
280 
285 inline void traverse_offset_bases(void *valueptr,
286  const detail::type_info *tinfo,
287  instance *self,
288  bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
289  for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
290  if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
291  for (auto &c : parent_tinfo->implicit_casts) {
292  if (c.first == tinfo->cpptype) {
293  auto *parentptr = c.second(valueptr);
294  if (parentptr != valueptr) {
295  f(parentptr, self);
296  }
297  traverse_offset_bases(parentptr, parent_tinfo, self, f);
298  break;
299  }
300  }
301  }
302  }
303 }
304 
305 inline bool register_instance_impl(void *ptr, instance *self) {
306  get_internals().registered_instances.emplace(ptr, self);
307  return true; // unused, but gives the same signature as the deregister func
308 }
309 inline bool deregister_instance_impl(void *ptr, instance *self) {
310  auto &registered_instances = get_internals().registered_instances;
311  auto range = registered_instances.equal_range(ptr);
312  for (auto it = range.first; it != range.second; ++it) {
313  if (self == it->second) {
314  registered_instances.erase(it);
315  return true;
316  }
317  }
318  return false;
319 }
320 
321 inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
322  register_instance_impl(valptr, self);
323  if (!tinfo->simple_ancestors) {
324  traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
325  }
326 }
327 
328 inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
329  bool ret = deregister_instance_impl(valptr, self);
330  if (!tinfo->simple_ancestors) {
331  traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
332  }
333  return ret;
334 }
335 
339 inline PyObject *make_new_instance(PyTypeObject *type) {
340 #if defined(PYPY_VERSION)
341  // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
342  // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
343  ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
344  if (type->tp_basicsize < instance_size) {
345  type->tp_basicsize = instance_size;
346  }
347 #endif
348  PyObject *self = type->tp_alloc(type, 0);
349  auto *inst = reinterpret_cast<instance *>(self);
350  // Allocate the value/holder internals:
351  inst->allocate_layout();
352 
353  return self;
354 }
355 
358 extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
359  return make_new_instance(type);
360 }
361 
365 extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
366  PyTypeObject *type = Py_TYPE(self);
367  std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
368  PyErr_SetString(PyExc_TypeError, msg.c_str());
369  return -1;
370 }
371 
372 inline void add_patient(PyObject *nurse, PyObject *patient) {
373  auto &internals = get_internals();
374  auto *instance = reinterpret_cast<detail::instance *>(nurse);
375  instance->has_patients = true;
376  Py_INCREF(patient);
377  internals.patients[nurse].push_back(patient);
378 }
379 
380 inline void clear_patients(PyObject *self) {
381  auto *instance = reinterpret_cast<detail::instance *>(self);
382  auto &internals = get_internals();
383  auto pos = internals.patients.find(self);
384  assert(pos != internals.patients.end());
385  // Clearing the patients can cause more Python code to run, which
386  // can invalidate the iterator. Extract the vector of patients
387  // from the unordered_map first.
388  auto patients = std::move(pos->second);
389  internals.patients.erase(pos);
390  instance->has_patients = false;
391  for (PyObject *&patient : patients) {
392  Py_CLEAR(patient);
393  }
394 }
395 
398 inline void clear_instance(PyObject *self) {
399  auto *instance = reinterpret_cast<detail::instance *>(self);
400 
401  // Deallocate any values/holders, if present:
402  for (auto &v_h : values_and_holders(instance)) {
403  if (v_h) {
404 
405  // We have to deregister before we call dealloc because, for virtual MI types, we still
406  // need to be able to get the parent pointers.
407  if (v_h.instance_registered()
408  && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
410  "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
411  }
412 
413  if (instance->owned || v_h.holder_constructed()) {
414  v_h.type->dealloc(v_h);
415  }
416  }
417  }
418  // Deallocate the value/holder layout internals:
420 
421  if (instance->weakrefs) {
422  PyObject_ClearWeakRefs(self);
423  }
424 
425  PyObject **dict_ptr = _PyObject_GetDictPtr(self);
426  if (dict_ptr) {
427  Py_CLEAR(*dict_ptr);
428  }
429 
430  if (instance->has_patients) {
431  clear_patients(self);
432  }
433 }
434 
437 extern "C" inline void pybind11_object_dealloc(PyObject *self) {
438  clear_instance(self);
439 
440  auto *type = Py_TYPE(self);
441  type->tp_free(self);
442 
443 #if PY_VERSION_HEX < 0x03080000
444  // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
445  // as part of a derived type's dealloc, in which case we're not allowed to decref
446  // the type here. For cross-module compatibility, we shouldn't compare directly
447  // with `pybind11_object_dealloc`, but with the common one stashed in internals.
448  auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
449  if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
450  Py_DECREF(type);
451 #else
452  // This was not needed before Python 3.8 (Python issue 35810)
453  // https://github.com/pybind/pybind11/issues/1946
454  Py_DECREF(type);
455 #endif
456 }
457 
458 std::string error_string();
459 
463 inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
464  constexpr auto *name = "pybind11_object";
465  auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
466 
467  /* Danger zone: from now (and until PyType_Ready), make sure to
468  issue no Python C API calls which could potentially invoke the
469  garbage collector (the GC will call type_traverse(), which will in
470  turn find the newly constructed type in an invalid state) */
471  auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
472  if (!heap_type) {
473  pybind11_fail("make_object_base_type(): error allocating type!");
474  }
475 
476  heap_type->ht_name = name_obj.inc_ref().ptr();
477 #ifdef PYBIND11_BUILTIN_QUALNAME
478  heap_type->ht_qualname = name_obj.inc_ref().ptr();
479 #endif
480 
481  auto *type = &heap_type->ht_type;
482  type->tp_name = name;
483  type->tp_base = type_incref(&PyBaseObject_Type);
484  type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
485  type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
486 
487  type->tp_new = pybind11_object_new;
488  type->tp_init = pybind11_object_init;
489  type->tp_dealloc = pybind11_object_dealloc;
490 
491  /* Support weak references (needed for the keep_alive feature) */
492  type->tp_weaklistoffset = offsetof(instance, weakrefs);
493 
494  if (PyType_Ready(type) < 0) {
495  pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
496  }
497 
498  setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
499  PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
500 
501  assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
502  return (PyObject *) heap_type;
503 }
504 
506 extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
507  PyObject *&dict = *_PyObject_GetDictPtr(self);
508  if (!dict) {
509  dict = PyDict_New();
510  }
511  Py_XINCREF(dict);
512  return dict;
513 }
514 
516 extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
517  if (!PyDict_Check(new_dict)) {
518  PyErr_Format(PyExc_TypeError,
519  "__dict__ must be set to a dictionary, not a '%.200s'",
520  get_fully_qualified_tp_name(Py_TYPE(new_dict)).c_str());
521  return -1;
522  }
523  PyObject *&dict = *_PyObject_GetDictPtr(self);
524  Py_INCREF(new_dict);
525  Py_CLEAR(dict);
526  dict = new_dict;
527  return 0;
528 }
529 
531 extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
532  PyObject *&dict = *_PyObject_GetDictPtr(self);
533  Py_VISIT(dict);
534 // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
535 #if PY_VERSION_HEX >= 0x03090000
536  Py_VISIT(Py_TYPE(self));
537 #endif
538  return 0;
539 }
540 
542 extern "C" inline int pybind11_clear(PyObject *self) {
543  PyObject *&dict = *_PyObject_GetDictPtr(self);
544  Py_CLEAR(dict);
545  return 0;
546 }
547 
549 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
550  auto *type = &heap_type->ht_type;
551  type->tp_flags |= Py_TPFLAGS_HAVE_GC;
552 #if PY_VERSION_HEX < 0x030B0000
553  type->tp_dictoffset = type->tp_basicsize; // place dict at the end
554  type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
555 #else
556  type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
557 #endif
558  type->tp_traverse = pybind11_traverse;
559  type->tp_clear = pybind11_clear;
560 
561  static PyGetSetDef getset[] = {
562  {const_cast<char *>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
563  {nullptr, nullptr, nullptr, nullptr, nullptr}};
564  type->tp_getset = getset;
565 }
566 
568 extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
569  // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
570  type_info *tinfo = nullptr;
571  for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
572  tinfo = get_type_info((PyTypeObject *) type.ptr());
573  if (tinfo && tinfo->get_buffer) {
574  break;
575  }
576  }
577  if (view == nullptr || !tinfo || !tinfo->get_buffer) {
578  if (view) {
579  view->obj = nullptr;
580  }
581  PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
582  return -1;
583  }
584  std::memset(view, 0, sizeof(Py_buffer));
585  buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
586  if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
587  delete info;
588  // view->obj = nullptr; // Was just memset to 0, so not necessary
589  PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
590  return -1;
591  }
592  view->obj = obj;
593  view->ndim = 1;
594  view->internal = info;
595  view->buf = info->ptr;
596  view->itemsize = info->itemsize;
597  view->len = view->itemsize;
598  for (auto s : info->shape) {
599  view->len *= s;
600  }
601  view->readonly = static_cast<int>(info->readonly);
602  if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
603  view->format = const_cast<char *>(info->format.c_str());
604  }
605  if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
606  view->ndim = (int) info->ndim;
607  view->strides = info->strides.data();
608  view->shape = info->shape.data();
609  }
610  Py_INCREF(view->obj);
611  return 0;
612 }
613 
615 extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
616  delete (buffer_info *) view->internal;
617 }
618 
620 inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
621  heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
622 
623  heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
624  heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
625 }
626 
629 inline PyObject *make_new_python_type(const type_record &rec) {
630  auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
631 
632  auto qualname = name;
633  if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
634  qualname = reinterpret_steal<object>(
635  PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
636  }
637 
638  object module_;
639  if (rec.scope) {
640  if (hasattr(rec.scope, "__module__")) {
641  module_ = rec.scope.attr("__module__");
642  } else if (hasattr(rec.scope, "__name__")) {
643  module_ = rec.scope.attr("__name__");
644  }
645  }
646 
647  const auto *full_name = c_str(
648 #if !defined(PYPY_VERSION)
649  module_ ? str(module_).cast<std::string>() + "." + rec.name :
650 #endif
651  rec.name);
652 
653  char *tp_doc = nullptr;
655  /* Allocate memory for docstring (using PyObject_MALLOC, since
656  Python will free this later on) */
657  size_t size = std::strlen(rec.doc) + 1;
658  tp_doc = (char *) PyObject_MALLOC(size);
659  std::memcpy((void *) tp_doc, rec.doc, size);
660  }
661 
662  auto &internals = get_internals();
663  auto bases = tuple(rec.bases);
664  auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
665 
666  /* Danger zone: from now (and until PyType_Ready), make sure to
667  issue no Python C API calls which could potentially invoke the
668  garbage collector (the GC will call type_traverse(), which will in
669  turn find the newly constructed type in an invalid state) */
670  auto *metaclass
671  = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
672 
673  auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
674  if (!heap_type) {
675  pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
676  }
677 
678  heap_type->ht_name = name.release().ptr();
679 #ifdef PYBIND11_BUILTIN_QUALNAME
680  heap_type->ht_qualname = qualname.inc_ref().ptr();
681 #endif
682 
683  auto *type = &heap_type->ht_type;
684  type->tp_name = full_name;
685  type->tp_doc = tp_doc;
686  type->tp_base = type_incref((PyTypeObject *) base);
687  type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
688  if (!bases.empty()) {
689  type->tp_bases = bases.release().ptr();
690  }
691 
692  /* Don't inherit base __init__ */
693  type->tp_init = pybind11_object_init;
694 
695  /* Supported protocols */
696  type->tp_as_number = &heap_type->as_number;
697  type->tp_as_sequence = &heap_type->as_sequence;
698  type->tp_as_mapping = &heap_type->as_mapping;
699  type->tp_as_async = &heap_type->as_async;
700 
701  /* Flags */
702  type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
703  if (!rec.is_final) {
704  type->tp_flags |= Py_TPFLAGS_BASETYPE;
705  }
706 
707  if (rec.dynamic_attr) {
708  enable_dynamic_attributes(heap_type);
709  }
710 
711  if (rec.buffer_protocol) {
712  enable_buffer_protocol(heap_type);
713  }
714 
715  if (rec.custom_type_setup_callback) {
716  rec.custom_type_setup_callback(heap_type);
717  }
718 
719  if (PyType_Ready(type) < 0) {
720  pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
721  }
722 
723  assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
724 
725  /* Register type with the parent scope */
726  if (rec.scope) {
727  setattr(rec.scope, rec.name, (PyObject *) type);
728  } else {
729  Py_INCREF(type); // Keep it alive forever (reference leak)
730  }
731 
732  if (module_) { // Needed by pydoc
733  setattr((PyObject *) type, "__module__", module_);
734  }
735 
737 
738  return (PyObject *) type;
739 }
740 
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
void * ptr
Definition: buffer_info.h:44
bool has_patients
If true, get_internals().patients has an entry for this object.
int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value)
Definition: class.h:127
PyObject * weakrefs
Weak references.
int pybind11_traverse(PyObject *self, visitproc visit, void *arg)
dynamic_attr: Allow the garbage collector to traverse the internal instance __dict__.
Definition: class.h:531
#define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
Definition: class.h:20
void deallocate_layout()
Destroys/deallocates all of the above.
bool is_final
Is the class inheritable from python classes?
Definition: attr.h:326
bool hasattr(handle obj, handle name)
Definition: pytypes.h:728
std::vector< ssize_t > strides
Definition: buffer_info.h:51
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
Annotation which requests that a special metaclass is created for a type.
Definition: attr.h:82
Definition: pytypes.h:2012
PyObject * instance_base
Definition: internals.h:170
bool readonly
Definition: buffer_info.h:53
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:405
void pybind11_object_dealloc(PyObject *self)
Definition: class.h:437
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
type_map< type_info * > registered_types_cpp
Definition: internals.h:152
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
bool buffer_protocol
Does the class implement the buffer protocol?
Definition: attr.h:317
Wrapper for Python extension modules.
Definition: pybind11.h:1136
const char * doc
Optional docstring.
Definition: attr.h:302
void clear_instance(PyObject *self)
Definition: class.h:398
void * get_buffer_data
Definition: internals.h:207
T cast() const
Definition: cast.h:1071
std::unordered_multimap< const void *, instance * > registered_instances
Definition: internals.h:155
Definition: cast.h:1238
bool deregister_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:328
The &#39;instance&#39; type which needs to be standard layout (need to be able to use &#39;offsetof&#39;) ...
static const symbolic::SymbolExpr< internal::symbolic_last_tag > last
const char * c_str(Args &&...args)
Definition: internals.h:524
int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *)
dynamic_attr: Support for instance.__dict__ = dict().
Definition: class.h:516
void pybind11_releasebuffer(PyObject *, Py_buffer *view)
buffer_protocol: Release the resources of the buffer.
Definition: class.h:615
bool deregister_instance_impl(void *ptr, instance *self)
Definition: class.h:309
PyExc_RuntimeError [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
custom_type_setup::callback custom_type_setup_callback
Custom type setup.
Definition: attr.h:308
PyTypeObject * type_incref(PyTypeObject *type)
Definition: class.h:40
void pybind11_meta_dealloc(PyObject *obj)
Cleanup the type-info for a pybind11-registered type.
Definition: class.h:200
else if n * info
PyObject * make_new_python_type(const type_record &rec)
Definition: class.h:629
PyObject * pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs)
metaclass __call__ function that is used to create all pybind11 objects.
Definition: class.h:174
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
void add_patient(PyObject *nurse, PyObject *patient)
Definition: class.h:372
handle metaclass
Custom metaclass (optional)
Definition: attr.h:305
PyTypeObject * static_property_type
Definition: internals.h:168
void clear_patients(PyObject *self)
Definition: class.h:380
Definition: descr.h:25
handle scope
Handle to the parent scope.
Definition: attr.h:272
ssize_t itemsize
Definition: buffer_info.h:45
int pybind11_clear(PyObject *self)
dynamic_attr: Allow the GC to clear the dictionary.
Definition: class.h:542
Values result
PyObject * pybind11_meta_getattro(PyObject *obj, PyObject *name)
Definition: class.h:164
int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value)
pybind11_static_property.__set__(): Just like the above __get__().
Definition: class.h:53
std::string format
Definition: buffer_info.h:47
const char * name
Name of the class.
Definition: attr.h:275
list bases
List of base classes of the newly created type.
Definition: attr.h:299
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:157
std::string get_fully_qualified_tp_name(PyTypeObject *type)
Definition: class.h:28
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:158
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:514
type_map< type_info * > registered_types_cpp
Definition: internals.h:476
void traverse_offset_bases(void *valueptr, const detail::type_info *tinfo, instance *self, bool(*f)(void *, instance *))
Definition: class.h:285
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
RealScalar s
PyObject * pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *)
Definition: class.h:358
PyObject * pybind11_get_dict(PyObject *self, void *)
dynamic_attr: Support for d = instance.__dict__.
Definition: class.h:506
std::vector< ssize_t > shape
Definition: buffer_info.h:50
PyObject * make_new_instance(PyTypeObject *type)
Definition: class.h:339
PyObject * make_object_base_type(PyTypeObject *metaclass)
Definition: class.h:463
DenseIndex ret
PyTypeObject * default_metaclass
Definition: internals.h:169
bool owned
If true, the pointer is owned which means we&#39;re free to manage it with a holder.
std::string error_string()
Definition: pytypes.h:578
const double h
handle release()
Definition: pytypes.h:330
Special data structure which (temporarily) holds metadata about a bound class.
Definition: attr.h:266
bool simple_ancestors
Definition: internals.h:215
bool register_instance_impl(void *ptr, instance *self)
Definition: class.h:305
Double_ range(const Point2_ &p, const Point2_ &q)
int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags)
buffer_protocol: Fill in the view as specified by flags.
Definition: class.h:568
int pybind11_object_init(PyObject *self, PyObject *, PyObject *)
Definition: class.h:365
std::unordered_map< const PyObject *, std::vector< PyObject * > > patients
Definition: internals.h:159
static bool show_user_defined_docstrings()
Definition: options.h:52
void enable_buffer_protocol(PyHeapTypeObject *heap_type)
Give this type a buffer interface.
Definition: class.h:620
Definition: pytypes.h:1924
Annotation for function names.
Definition: attr.h:48
Annotation indicating that a class derives from another given type.
Definition: attr.h:61
Information record describing a Python buffer object.
Definition: buffer_info.h:43
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:238
ssize_t ndim
Definition: buffer_info.h:49
PyTypeObject * make_static_property_type()
Definition: class.h:61
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:154
buffer_info *(* get_buffer)(PyObject *, void *)
Definition: internals.h:206
void register_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:321
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:780
PyTypeObject * make_default_metaclass()
Definition: class.h:241
#define PYBIND11_NAMESPACE_END(name)
bool dynamic_attr
Does the class manage a dict?
Definition: attr.h:314
Definition: pytypes.h:1370
#define PYBIND11_NAMESPACE_BEGIN(name)
void enable_dynamic_attributes(PyHeapTypeObject *heap_type)
Give instances of this type a __dict__ and opt into garbage collection.
Definition: class.h:549


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:34:01