μ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 PY_VERSION_HEX >= 0x03030000 && !defined(PYPY_VERSION)
19# define PYBIND11_BUILTIN_QUALNAME
20# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
21#else
22// In pre-3.3 Python, we still set __qualname__ so that we can produce reliable function type
23// signatures; in 3.3+ 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
61inline 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"));
92
93 return type;
94}
95
96#else // PYPY
97
101inline PyTypeObject *make_static_property_type() {
102 auto d = dict();
103 PyObject *result = PyRun_String(R"(\
104class 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
127extern "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
158#if PY_MAJOR_VERSION >= 3
165extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
166 PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
167 if (descr && PyInstanceMethod_Check(descr)) {
168 Py_INCREF(descr);
169 return descr;
170 }
171 return PyType_Type.tp_getattro(obj, name);
172}
173#endif
174
176extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
177
178 // use the default metaclass call to create/initialize the object
179 PyObject *self = PyType_Type.tp_call(type, args, kwargs);
180 if (self == nullptr) {
181 return nullptr;
182 }
183
184 // This must be a pybind11 instance
185 auto *instance = reinterpret_cast<detail::instance *>(self);
186
187 // Ensure that the base __init__ function(s) were called
188 for (const auto &vh : values_and_holders(instance)) {
189 if (!vh.holder_constructed()) {
190 PyErr_Format(PyExc_TypeError,
191 "%.200s.__init__() must be called when overriding __init__",
192 get_fully_qualified_tp_name(vh.type->type).c_str());
193 Py_DECREF(self);
194 return nullptr;
195 }
196 }
197
198 return self;
199}
200
202extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
203 auto *type = (PyTypeObject *) obj;
204 auto &internals = get_internals();
205
206 // A pybind11-registered type will:
207 // 1) be found in internals.registered_types_py
208 // 2) have exactly one associated `detail::type_info`
209 auto found_type = internals.registered_types_py.find(type);
210 if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
211 && found_type->second[0]->type == type) {
212
213 auto *tinfo = found_type->second[0];
214 auto tindex = std::type_index(*tinfo->cpptype);
215 internals.direct_conversions.erase(tindex);
216
217 if (tinfo->module_local) {
219 } else {
220 internals.registered_types_cpp.erase(tindex);
221 }
222 internals.registered_types_py.erase(tinfo->type);
223
224 // Actually just `std::erase_if`, but that's only available in C++20
226 for (auto it = cache.begin(), last = cache.end(); it != last;) {
227 if (it->first == (PyObject *) tinfo->type) {
228 it = cache.erase(it);
229 } else {
230 ++it;
231 }
232 }
233
234 delete tinfo;
235 }
236
237 PyType_Type.tp_dealloc(obj);
238}
239
243inline PyTypeObject *make_default_metaclass() {
244 constexpr auto *name = "pybind11_type";
245 auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
246
247 /* Danger zone: from now (and until PyType_Ready), make sure to
248 issue no Python C API calls which could potentially invoke the
249 garbage collector (the GC will call type_traverse(), which will in
250 turn find the newly constructed type in an invalid state) */
251 auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
252 if (!heap_type) {
253 pybind11_fail("make_default_metaclass(): error allocating metaclass!");
254 }
255
256 heap_type->ht_name = name_obj.inc_ref().ptr();
257#ifdef PYBIND11_BUILTIN_QUALNAME
258 heap_type->ht_qualname = name_obj.inc_ref().ptr();
259#endif
260
261 auto *type = &heap_type->ht_type;
262 type->tp_name = name;
263 type->tp_base = type_incref(&PyType_Type);
264 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
265
266 type->tp_call = pybind11_meta_call;
267
268 type->tp_setattro = pybind11_meta_setattro;
269#if PY_MAJOR_VERSION >= 3
270 type->tp_getattro = pybind11_meta_getattro;
271#endif
272
273 type->tp_dealloc = pybind11_meta_dealloc;
274
275 if (PyType_Ready(type) < 0) {
276 pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
277 }
278
279 setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
281
282 return type;
283}
284
289inline void traverse_offset_bases(void *valueptr,
290 const detail::type_info *tinfo,
291 instance *self,
292 bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
293 for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
294 if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
295 for (auto &c : parent_tinfo->implicit_casts) {
296 if (c.first == tinfo->cpptype) {
297 auto *parentptr = c.second(valueptr);
298 if (parentptr != valueptr) {
299 f(parentptr, self);
300 }
301 traverse_offset_bases(parentptr, parent_tinfo, self, f);
302 break;
303 }
304 }
305 }
306 }
307}
308
309inline bool register_instance_impl(void *ptr, instance *self) {
311 return true; // unused, but gives the same signature as the deregister func
312}
313inline bool deregister_instance_impl(void *ptr, instance *self) {
314 auto &registered_instances = get_internals().registered_instances;
315 auto range = registered_instances.equal_range(ptr);
316 for (auto it = range.first; it != range.second; ++it) {
317 if (self == it->second) {
318 registered_instances.erase(it);
319 return true;
320 }
321 }
322 return false;
323}
324
325inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
327 if (!tinfo->simple_ancestors) {
329 }
330}
331
332inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
333 bool ret = deregister_instance_impl(valptr, self);
334 if (!tinfo->simple_ancestors) {
336 }
337 return ret;
338}
339
343inline PyObject *make_new_instance(PyTypeObject *type) {
344#if defined(PYPY_VERSION)
345 // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
346 // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
347 ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
348 if (type->tp_basicsize < instance_size) {
349 type->tp_basicsize = instance_size;
350 }
351#endif
352 PyObject *self = type->tp_alloc(type, 0);
353 auto *inst = reinterpret_cast<instance *>(self);
354 // Allocate the value/holder internals:
355 inst->allocate_layout();
356
357 return self;
358}
359
362extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
363 return make_new_instance(type);
364}
365
369extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
370 PyTypeObject *type = Py_TYPE(self);
371 std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
372 PyErr_SetString(PyExc_TypeError, msg.c_str());
373 return -1;
374}
375
376inline void add_patient(PyObject *nurse, PyObject *patient) {
377 auto &internals = get_internals();
378 auto *instance = reinterpret_cast<detail::instance *>(nurse);
379 instance->has_patients = true;
380 Py_INCREF(patient);
381 internals.patients[nurse].push_back(patient);
382}
383
384inline void clear_patients(PyObject *self) {
385 auto *instance = reinterpret_cast<detail::instance *>(self);
386 auto &internals = get_internals();
387 auto pos = internals.patients.find(self);
388 assert(pos != internals.patients.end());
389 // Clearing the patients can cause more Python code to run, which
390 // can invalidate the iterator. Extract the vector of patients
391 // from the unordered_map first.
392 auto patients = std::move(pos->second);
393 internals.patients.erase(pos);
394 instance->has_patients = false;
395 for (PyObject *&patient : patients) {
396 Py_CLEAR(patient);
397 }
398}
399
402inline void clear_instance(PyObject *self) {
403 auto *instance = reinterpret_cast<detail::instance *>(self);
404
405 // Deallocate any values/holders, if present:
406 for (auto &v_h : values_and_holders(instance)) {
407 if (v_h) {
408
409 // We have to deregister before we call dealloc because, for virtual MI types, we still
410 // need to be able to get the parent pointers.
411 if (v_h.instance_registered()
412 && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
414 "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
415 }
416
417 if (instance->owned || v_h.holder_constructed()) {
418 v_h.type->dealloc(v_h);
419 }
420 }
421 }
422 // Deallocate the value/holder layout internals:
424
425 if (instance->weakrefs) {
426 PyObject_ClearWeakRefs(self);
427 }
428
429 PyObject **dict_ptr = _PyObject_GetDictPtr(self);
430 if (dict_ptr) {
431 Py_CLEAR(*dict_ptr);
432 }
433
434 if (instance->has_patients) {
436 }
437}
438
441extern "C" inline void pybind11_object_dealloc(PyObject *self) {
443
444 auto *type = Py_TYPE(self);
445 type->tp_free(self);
446
447#if PY_VERSION_HEX < 0x03080000
448 // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
449 // as part of a derived type's dealloc, in which case we're not allowed to decref
450 // the type here. For cross-module compatibility, we shouldn't compare directly
451 // with `pybind11_object_dealloc`, but with the common one stashed in internals.
452 auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
453 if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
454 Py_DECREF(type);
455#else
456 // This was not needed before Python 3.8 (Python issue 35810)
457 // https://github.com/pybind/pybind11/issues/1946
458 Py_DECREF(type);
459#endif
460}
461
465inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
466 constexpr auto *name = "pybind11_object";
467 auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
468
469 /* Danger zone: from now (and until PyType_Ready), make sure to
470 issue no Python C API calls which could potentially invoke the
471 garbage collector (the GC will call type_traverse(), which will in
472 turn find the newly constructed type in an invalid state) */
473 auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
474 if (!heap_type) {
475 pybind11_fail("make_object_base_type(): error allocating type!");
476 }
477
478 heap_type->ht_name = name_obj.inc_ref().ptr();
479#ifdef PYBIND11_BUILTIN_QUALNAME
480 heap_type->ht_qualname = name_obj.inc_ref().ptr();
481#endif
482
483 auto *type = &heap_type->ht_type;
484 type->tp_name = name;
485 type->tp_base = type_incref(&PyBaseObject_Type);
486 type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
487 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
488
489 type->tp_new = pybind11_object_new;
490 type->tp_init = pybind11_object_init;
491 type->tp_dealloc = pybind11_object_dealloc;
492
493 /* Support weak references (needed for the keep_alive feature) */
494 type->tp_weaklistoffset = offsetof(instance, weakrefs);
495
496 if (PyType_Ready(type) < 0) {
497 pybind11_fail("PyType_Ready failed in make_object_base_type():" + error_string());
498 }
499
500 setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
502
503 assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
504 return (PyObject *) heap_type;
505}
506
508extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
509 PyObject *&dict = *_PyObject_GetDictPtr(self);
510 if (!dict) {
511 dict = PyDict_New();
512 }
513 Py_XINCREF(dict);
514 return dict;
515}
516
518extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
519 if (!PyDict_Check(new_dict)) {
520 PyErr_Format(PyExc_TypeError,
521 "__dict__ must be set to a dictionary, not a '%.200s'",
522 get_fully_qualified_tp_name(Py_TYPE(new_dict)).c_str());
523 return -1;
524 }
525 PyObject *&dict = *_PyObject_GetDictPtr(self);
526 Py_INCREF(new_dict);
527 Py_CLEAR(dict);
528 dict = new_dict;
529 return 0;
530}
531
533extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
534 PyObject *&dict = *_PyObject_GetDictPtr(self);
535 Py_VISIT(dict);
536 return 0;
537}
538
540extern "C" inline int pybind11_clear(PyObject *self) {
541 PyObject *&dict = *_PyObject_GetDictPtr(self);
542 Py_CLEAR(dict);
543 return 0;
544}
545
547inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
548 auto *type = &heap_type->ht_type;
549 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
550 type->tp_dictoffset = type->tp_basicsize; // place dict at the end
551 type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
552 type->tp_traverse = pybind11_traverse;
553 type->tp_clear = pybind11_clear;
554
555 static PyGetSetDef getset[] = {
556 {const_cast<char *>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
557 {nullptr, nullptr, nullptr, nullptr, nullptr}};
558 type->tp_getset = getset;
559}
560
562extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
563 // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
564 type_info *tinfo = nullptr;
565 for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
566 tinfo = get_type_info((PyTypeObject *) type.ptr());
567 if (tinfo && tinfo->get_buffer) {
568 break;
569 }
570 }
571 if (view == nullptr || !tinfo || !tinfo->get_buffer) {
572 if (view) {
573 view->obj = nullptr;
574 }
575 PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
576 return -1;
577 }
578 std::memset(view, 0, sizeof(Py_buffer));
579 buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
580 if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
581 delete info;
582 // view->obj = nullptr; // Was just memset to 0, so not necessary
583 PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
584 return -1;
585 }
586 view->obj = obj;
587 view->ndim = 1;
588 view->internal = info;
589 view->buf = info->ptr;
590 view->itemsize = info->itemsize;
591 view->len = view->itemsize;
592 for (auto s : info->shape) {
593 view->len *= s;
594 }
595 view->readonly = static_cast<int>(info->readonly);
596 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
597 view->format = const_cast<char *>(info->format.c_str());
598 }
599 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
600 view->ndim = (int) info->ndim;
601 view->strides = info->strides.data();
602 view->shape = info->shape.data();
603 }
604 Py_INCREF(view->obj);
605 return 0;
606}
607
609extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
610 delete (buffer_info *) view->internal;
611}
612
614inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
615 heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
616#if PY_MAJOR_VERSION < 3
617 heap_type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
618#endif
619
620 heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
621 heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
622}
623
626inline PyObject *make_new_python_type(const type_record &rec) {
627 auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
628
629 auto qualname = name;
630 if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
631#if PY_MAJOR_VERSION >= 3
632 qualname = reinterpret_steal<object>(
633 PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
634#else
635 qualname = str(rec.scope.attr("__qualname__").cast<std::string>() + "." + rec.name);
636#endif
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#if PY_VERSION_HEX >= 0x03050000
701 type->tp_as_async = &heap_type->as_async;
702#endif
703
704 /* Flags */
705 type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
706#if PY_MAJOR_VERSION < 3
707 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
708#endif
709 if (!rec.is_final) {
710 type->tp_flags |= Py_TPFLAGS_BASETYPE;
711 }
712
713 if (rec.dynamic_attr) {
714 enable_dynamic_attributes(heap_type);
715 }
716
717 if (rec.buffer_protocol) {
718 enable_buffer_protocol(heap_type);
719 }
720
722 rec.custom_type_setup_callback(heap_type);
723 }
724
725 if (PyType_Ready(type) < 0) {
726 pybind11_fail(std::string(rec.name) + ": PyType_Ready failed (" + error_string() + ")!");
727 }
728
729 assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
730
731 /* Register type with the parent scope */
732 if (rec.scope) {
733 setattr(rec.scope, rec.name, (PyObject *) type);
734 } else {
735 Py_INCREF(type); // Keep it alive forever (reference leak)
736 }
737
738 if (module_) { // Needed by pydoc
739 setattr((PyObject *) type, "__module__", module_);
740 }
741
743
744 return (PyObject *) type;
745}
746
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
PyObject * pybind11_get_dict(PyObject *self, void *)
dynamic_attr: Support for d = instance.__dict__.
Definition: class.h:508
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
int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *)
dynamic_attr: Support for instance.__dict__ = dict().
Definition: class.h:518
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