μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
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
28inline 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>();
33 if (module_name == PYBIND11_BUILTINS_MODULE)
34 return type->tp_name;
35 else
36 return std::move(module_name) + "." + type->tp_name;
37#endif
38}
39
40inline PyTypeObject *type_incref(PyTypeObject *type) {
41 Py_INCREF(type);
42 return type;
43}
44
45#if !defined(PYPY_VERSION)
46
48extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
49 return PyProperty_Type.tp_descr_get(self, cls, cls);
50}
51
53extern "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()`
59inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
60
64inline 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__`)
98# endif
99
100 setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
102
103 return type;
104}
105
106#else // PYPY
107
111inline PyTypeObject *make_static_property_type() {
112 auto d = dict();
113 PyObject *result = PyRun_String(R"(\
114class 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
137extern "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
174extern "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
184extern "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
210extern "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
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
251inline 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
295inline 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
315inline bool register_instance_impl(void *ptr, instance *self) {
317 return true; // unused, but gives the same signature as the deregister func
318}
319inline 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
331inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
333 if (!tinfo->simple_ancestors) {
335 }
336}
337
338inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
339 bool ret = deregister_instance_impl(valptr, self);
340 if (!tinfo->simple_ancestors) {
342 }
343 return ret;
344}
345
349inline 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
368extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
369 return make_new_instance(type);
370}
371
375extern "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
382inline 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
390inline 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
408inline 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) {
442 }
443}
444
447extern "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
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
476std::string error_string();
477
481inline 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
524extern "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
535extern "C" inline int pybind11_clear(PyObject *self) {
536 PyObject *&dict = *_PyObject_GetDictPtr(self);
537 Py_CLEAR(dict);
538 return 0;
539}
540
542inline 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
569extern "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
616extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
617 delete (buffer_info *) view->internal;
618}
619
621inline 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
630inline 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
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
Definition: pytypes.h:1776
Definition: pytypes.h:1694
Fetch and hold an error which was already set in Python.
Definition: pytypes.h:379
\rst Holds a reference to a Python object (no reference counting)
Definition: pytypes.h:194
T cast() const
\rst Attempt to cast the Python object into the given C++ type.
Definition: cast.h:1083
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:203
Wrapper for Python extension modules.
Definition: pybind11.h:1145
handle release()
\rst Resets the internal pointer to nullptr without decreasing the object's reference count.
Definition: pytypes.h:283
static bool show_user_defined_docstrings()
Definition: options.h:52
Definition: pytypes.h:1200
Definition: pytypes.h:1167
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:569
bool hasattr(handle obj, handle name)
Definition: pytypes.h:517
void enable_buffer_protocol(PyHeapTypeObject *heap_type)
Give this type a buffer interface.
Definition: class.h:614
PyObject * pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *)
Instance creation function for all pybind11 types.
Definition: class.h:362
PyTypeObject * make_default_metaclass()
This metaclass is assigned by default to all pybind11 types and is required in order for static prope...
Definition: class.h:243
PyObject * make_object_base_type(PyTypeObject *metaclass)
Create the type which can be used as a common base for all classes.
Definition: class.h:465
PyTypeObject * type_incref(PyTypeObject *type)
Definition: class.h:40
std::string get_fully_qualified_tp_name(PyTypeObject *type)
Definition: class.h:28
int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value)
pybind11_static_property.__set__(): Just like the above __get__().
Definition: class.h:53
int pybind11_object_init(PyObject *self, PyObject *, PyObject *)
An __init__ function constructs the C++ object.
Definition: class.h:369
void clear_patients(PyObject *self)
Definition: class.h:384
bool deregister_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:332
void pybind11_releasebuffer(PyObject *, Py_buffer *view)
buffer_protocol: Release the resources of the buffer.
Definition: class.h:609
#define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
Definition: class.h:24
int pybind11_clear(PyObject *self)
dynamic_attr: Allow the GC to clear the dictionary.
Definition: class.h:540
void pybind11_object_dealloc(PyObject *self)
Instance destructor function for all pybind11 types.
Definition: class.h:441
void clear_instance(PyObject *self)
Clears all internal data from the instance and removes it from registered instances in preparation fo...
Definition: class.h:402
void register_instance(instance *self, void *valptr, const type_info *tinfo)
Definition: class.h:325
void enable_dynamic_attributes(PyHeapTypeObject *heap_type)
Give instances of this type a __dict__ and opt into garbage collection.
Definition: class.h:547
int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value)
Types with static properties need to handle Type.static_prop = x in a specific way.
Definition: class.h:127
PyTypeObject * make_static_property_type()
A static_property is the same as a property but the __get__() and __set__() methods are modified to a...
Definition: class.h:61
int pybind11_traverse(PyObject *self, visitproc visit, void *arg)
dynamic_attr: Allow the garbage collector to traverse the internal instance __dict__.
Definition: class.h:533
bool deregister_instance_impl(void *ptr, instance *self)
Definition: class.h:313
PyObject * make_new_instance(PyTypeObject *type)
Instance creation function for all pybind11 types.
Definition: class.h:343
PyObject * make_new_python_type(const type_record &rec)
Create a brand new Python type according to the type_record specification.
Definition: class.h:626
bool register_instance_impl(void *ptr, instance *self)
Definition: class.h:309
void add_patient(PyObject *nurse, PyObject *patient)
Definition: class.h:376
void traverse_offset_bases(void *valueptr, const detail::type_info *tinfo, instance *self, bool(*f)(void *, instance *))
For multiple inheritance types we need to recursively register/deregister base pointers for any base ...
Definition: class.h:289
int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags)
buffer_protocol: Fill in the view as specified by flags.
Definition: class.h:562
void pybind11_meta_dealloc(PyObject *obj)
Cleanup the type-info for a pybind11-registered type.
Definition: class.h:202
PyObject * pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs)
metaclass __call__ function that is used to create all pybind11 objects.
Definition: class.h:176
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
constexpr int last(int, int result)
Definition: common.h:801
PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Thrown when pybind11::cast or.
Definition: common.h:992
#define PYBIND11_FROM_STRING
Definition: common.h:319
#define PYBIND11_BUILTINS_MODULE
Definition: common.h:323
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:21
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:20
Py_ssize_t ssize_t
Definition: common.h:460
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:416
const char * c_str(Args &&...args)
Constructs a std::string with the given arguments, stores it in internals, and returns its c_str().
Definition: internals.h:534
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:524
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
Gets a single pybind11 type info for a python type.
PYBIND11_NOINLINE std::string error_string()
static const self_t self
Definition: operators.h:72
PyObject * pybind11_meta_getattro(PyObject *obj, PyObject *name)
Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing methods v...
Definition: class.h:174
Annotation for arguments.
Definition: cast.h:1238
Annotation indicating that a class derives from another given type.
Definition: attr.h:60
Information record describing a Python buffer object.
Definition: buffer_info.h:43
std::vector< ssize_t > shape
Definition: buffer_info.h:50
std::vector< ssize_t > strides
Definition: buffer_info.h:51
ssize_t ndim
Definition: buffer_info.h:49
ssize_t itemsize
Definition: buffer_info.h:45
bool readonly
Definition: buffer_info.h:53
void * ptr
Definition: buffer_info.h:44
std::string format
Definition: buffer_info.h:47
Definition: descr.h:25
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Definition: common.h:554
void deallocate_layout()
Destroys/deallocates all of the above.
bool has_patients
If true, get_internals().patients has an entry for this object.
Definition: common.h:594
PyObject * weakrefs
Weak references.
Definition: common.h:562
bool owned
If true, the pointer is owned which means we're free to manage it with a holder.
Definition: common.h:564
void allocate_layout()
Initializes all of the above type/values/holders data (but not the instance values themselves)
Internal data structure used to track registered instances and types.
Definition: internals.h:150
type_map< type_info * > registered_types_cpp
Definition: internals.h:152
std::unordered_multimap< const void *, instance * > registered_instances
Definition: internals.h:155
std::unordered_map< const PyObject *, std::vector< PyObject * > > patients
Definition: internals.h:159
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:154
PyTypeObject * static_property_type
Definition: internals.h:168
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:158
PyTypeObject * default_metaclass
Definition: internals.h:169
PyObject * instance_base
Definition: internals.h:170
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:157
type_map< type_info * > registered_types_cpp
Definition: internals.h:486
Annotation which requests that a special metaclass is created for a type.
Definition: attr.h:81
Annotation for function names.
Definition: attr.h:47
Additional type information which does not fit into the PyTypeObject.
Definition: internals.h:196
buffer_info *(* get_buffer)(PyObject *, void *)
Definition: internals.h:206
bool simple_ancestors
Definition: internals.h:215
void * get_buffer_data
Definition: internals.h:207
Special data structure which (temporarily) holds metadata about a bound class.
Definition: attr.h:266
handle metaclass
Custom metaclass (optional)
Definition: attr.h:305
const char * name
Name of the class.
Definition: attr.h:275
bool is_final
Is the class inheritable from python classes?
Definition: attr.h:326
handle scope
Handle to the parent scope.
Definition: attr.h:272
bool buffer_protocol
Does the class implement the buffer protocol?
Definition: attr.h:317
const char * doc
Optional docstring.
Definition: attr.h:302
list bases
List of base classes of the newly created type.
Definition: attr.h:299
custom_type_setup::callback custom_type_setup_callback
Custom type setup.
Definition: attr.h:308
bool dynamic_attr
Does the class manage a dict?
Definition: attr.h:314