Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:06:11

0001 /*
0002     pybind11/detail/class.h: Python C API implementation details for py::class_
0003 
0004     Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
0005 
0006     All rights reserved. Use of this source code is governed by a
0007     BSD-style license that can be found in the LICENSE file.
0008 */
0009 
0010 #pragma once
0011 
0012 #include <pybind11/attr.h>
0013 #include <pybind11/options.h>
0014 
0015 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0016 PYBIND11_NAMESPACE_BEGIN(detail)
0017 
0018 #if !defined(PYPY_VERSION)
0019 #    define PYBIND11_BUILTIN_QUALNAME
0020 #    define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
0021 #else
0022 // In PyPy, we still set __qualname__ so that we can produce reliable function type
0023 // signatures; in CPython this macro expands to nothing:
0024 #    define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)                                             \
0025         setattr((PyObject *) obj, "__qualname__", nameobj)
0026 #endif
0027 
0028 inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
0029 #if !defined(PYPY_VERSION)
0030     return type->tp_name;
0031 #else
0032     auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
0033     if (module_name == PYBIND11_BUILTINS_MODULE)
0034         return type->tp_name;
0035     else
0036         return std::move(module_name) + "." + type->tp_name;
0037 #endif
0038 }
0039 
0040 inline PyTypeObject *type_incref(PyTypeObject *type) {
0041     Py_INCREF(type);
0042     return type;
0043 }
0044 
0045 #if !defined(PYPY_VERSION)
0046 
0047 /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
0048 extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
0049     return PyProperty_Type.tp_descr_get(self, cls, cls);
0050 }
0051 
0052 /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
0053 extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
0054     PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
0055     return PyProperty_Type.tp_descr_set(self, cls, value);
0056 }
0057 
0058 // Forward declaration to use in `make_static_property_type()`
0059 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
0060 
0061 /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
0062     methods are modified to always use the object type instead of a concrete instance.
0063     Return value: New reference. */
0064 inline PyTypeObject *make_static_property_type() {
0065     constexpr auto *name = "pybind11_static_property";
0066     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
0067 
0068     /* Danger zone: from now (and until PyType_Ready), make sure to
0069        issue no Python C API calls which could potentially invoke the
0070        garbage collector (the GC will call type_traverse(), which will in
0071        turn find the newly constructed type in an invalid state) */
0072     auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
0073     if (!heap_type) {
0074         pybind11_fail("make_static_property_type(): error allocating type!");
0075     }
0076 
0077     heap_type->ht_name = name_obj.inc_ref().ptr();
0078 #    ifdef PYBIND11_BUILTIN_QUALNAME
0079     heap_type->ht_qualname = name_obj.inc_ref().ptr();
0080 #    endif
0081 
0082     auto *type = &heap_type->ht_type;
0083     type->tp_name = name;
0084     type->tp_base = type_incref(&PyProperty_Type);
0085     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
0086     type->tp_descr_get = pybind11_static_get;
0087     type->tp_descr_set = pybind11_static_set;
0088 
0089 #    if PY_VERSION_HEX >= 0x030C0000
0090     // Since Python-3.12 property-derived types are required to
0091     // have dynamic attributes (to set `__doc__`)
0092     enable_dynamic_attributes(heap_type);
0093 #    endif
0094 
0095     if (PyType_Ready(type) < 0) {
0096         pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
0097     }
0098 
0099     setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
0100     PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
0101 
0102     return type;
0103 }
0104 
0105 #else // PYPY
0106 
0107 /** PyPy has some issues with the above C API, so we evaluate Python code instead.
0108     This function will only be called once so performance isn't really a concern.
0109     Return value: New reference. */
0110 inline PyTypeObject *make_static_property_type() {
0111     auto d = dict();
0112     PyObject *result = PyRun_String(R"(\
0113 class pybind11_static_property(property):
0114     def __get__(self, obj, cls):
0115         return property.__get__(self, cls, cls)
0116 
0117     def __set__(self, obj, value):
0118         cls = obj if isinstance(obj, type) else type(obj)
0119         property.__set__(self, cls, value)
0120 )",
0121                                     Py_file_input,
0122                                     d.ptr(),
0123                                     d.ptr());
0124     if (result == nullptr)
0125         throw error_already_set();
0126     Py_DECREF(result);
0127     return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
0128 }
0129 
0130 #endif // PYPY
0131 
0132 /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
0133     By default, Python replaces the `static_property` itself, but for wrapped C++ types
0134     we need to call `static_property.__set__()` in order to propagate the new value to
0135     the underlying C++ data structure. */
0136 extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
0137     // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
0138     // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
0139     PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
0140 
0141     // The following assignment combinations are possible:
0142     //   1. `Type.static_prop = value`             --> descr_set: `Type.static_prop.__set__(value)`
0143     //   2. `Type.static_prop = other_static_prop` --> setattro:  replace existing `static_prop`
0144     //   3. `Type.regular_attribute = value`       --> setattro:  regular attribute assignment
0145     auto *const static_prop = (PyObject *) get_internals().static_property_type;
0146     const auto call_descr_set = (descr != nullptr) && (value != nullptr)
0147                                 && (PyObject_IsInstance(descr, static_prop) != 0)
0148                                 && (PyObject_IsInstance(value, static_prop) == 0);
0149     if (call_descr_set) {
0150         // Call `static_property.__set__()` instead of replacing the `static_property`.
0151 #if !defined(PYPY_VERSION)
0152         return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
0153 #else
0154         if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
0155             Py_DECREF(result);
0156             return 0;
0157         } else {
0158             return -1;
0159         }
0160 #endif
0161     } else {
0162         // Replace existing attribute.
0163         return PyType_Type.tp_setattro(obj, name, value);
0164     }
0165 }
0166 
0167 /**
0168  * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
0169  * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
0170  * when called on a class, or a PyMethod, when called on an instance.  Override that behaviour here
0171  * to do a special case bypass for PyInstanceMethod_Types.
0172  */
0173 extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
0174     PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
0175     if (descr && PyInstanceMethod_Check(descr)) {
0176         Py_INCREF(descr);
0177         return descr;
0178     }
0179     return PyType_Type.tp_getattro(obj, name);
0180 }
0181 
0182 /// metaclass `__call__` function that is used to create all pybind11 objects.
0183 extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
0184 
0185     // use the default metaclass call to create/initialize the object
0186     PyObject *self = PyType_Type.tp_call(type, args, kwargs);
0187     if (self == nullptr) {
0188         return nullptr;
0189     }
0190 
0191     // Ensure that the base __init__ function(s) were called
0192     values_and_holders vhs(self);
0193     for (const auto &vh : vhs) {
0194         if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) {
0195             PyErr_Format(PyExc_TypeError,
0196                          "%.200s.__init__() must be called when overriding __init__",
0197                          get_fully_qualified_tp_name(vh.type->type).c_str());
0198             Py_DECREF(self);
0199             return nullptr;
0200         }
0201     }
0202 
0203     return self;
0204 }
0205 
0206 /// Cleanup the type-info for a pybind11-registered type.
0207 extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
0208     with_internals([obj](internals &internals) {
0209         auto *type = (PyTypeObject *) obj;
0210 
0211         // A pybind11-registered type will:
0212         // 1) be found in internals.registered_types_py
0213         // 2) have exactly one associated `detail::type_info`
0214         auto found_type = internals.registered_types_py.find(type);
0215         if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
0216             && found_type->second[0]->type == type) {
0217 
0218             auto *tinfo = found_type->second[0];
0219             auto tindex = std::type_index(*tinfo->cpptype);
0220             internals.direct_conversions.erase(tindex);
0221 
0222             if (tinfo->module_local) {
0223                 get_local_internals().registered_types_cpp.erase(tindex);
0224             } else {
0225                 internals.registered_types_cpp.erase(tindex);
0226             }
0227             internals.registered_types_py.erase(tinfo->type);
0228 
0229             // Actually just `std::erase_if`, but that's only available in C++20
0230             auto &cache = internals.inactive_override_cache;
0231             for (auto it = cache.begin(), last = cache.end(); it != last;) {
0232                 if (it->first == (PyObject *) tinfo->type) {
0233                     it = cache.erase(it);
0234                 } else {
0235                     ++it;
0236                 }
0237             }
0238 
0239             delete tinfo;
0240         }
0241     });
0242 
0243     PyType_Type.tp_dealloc(obj);
0244 }
0245 
0246 /** This metaclass is assigned by default to all pybind11 types and is required in order
0247     for static properties to function correctly. Users may override this using `py::metaclass`.
0248     Return value: New reference. */
0249 inline PyTypeObject *make_default_metaclass() {
0250     constexpr auto *name = "pybind11_type";
0251     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
0252 
0253     /* Danger zone: from now (and until PyType_Ready), make sure to
0254        issue no Python C API calls which could potentially invoke the
0255        garbage collector (the GC will call type_traverse(), which will in
0256        turn find the newly constructed type in an invalid state) */
0257     auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
0258     if (!heap_type) {
0259         pybind11_fail("make_default_metaclass(): error allocating metaclass!");
0260     }
0261 
0262     heap_type->ht_name = name_obj.inc_ref().ptr();
0263 #ifdef PYBIND11_BUILTIN_QUALNAME
0264     heap_type->ht_qualname = name_obj.inc_ref().ptr();
0265 #endif
0266 
0267     auto *type = &heap_type->ht_type;
0268     type->tp_name = name;
0269     type->tp_base = type_incref(&PyType_Type);
0270     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
0271 
0272     type->tp_call = pybind11_meta_call;
0273 
0274     type->tp_setattro = pybind11_meta_setattro;
0275     type->tp_getattro = pybind11_meta_getattro;
0276 
0277     type->tp_dealloc = pybind11_meta_dealloc;
0278 
0279     if (PyType_Ready(type) < 0) {
0280         pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
0281     }
0282 
0283     setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
0284     PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
0285 
0286     return type;
0287 }
0288 
0289 /// For multiple inheritance types we need to recursively register/deregister base pointers for any
0290 /// base classes with pointers that are difference from the instance value pointer so that we can
0291 /// correctly recognize an offset base class pointer. This calls a function with any offset base
0292 /// ptrs.
0293 inline void traverse_offset_bases(void *valueptr,
0294                                   const detail::type_info *tinfo,
0295                                   instance *self,
0296                                   bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
0297     for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
0298         if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
0299             for (auto &c : parent_tinfo->implicit_casts) {
0300                 if (c.first == tinfo->cpptype) {
0301                     auto *parentptr = c.second(valueptr);
0302                     if (parentptr != valueptr) {
0303                         f(parentptr, self);
0304                     }
0305                     traverse_offset_bases(parentptr, parent_tinfo, self, f);
0306                     break;
0307                 }
0308             }
0309         }
0310     }
0311 }
0312 
0313 inline bool register_instance_impl(void *ptr, instance *self) {
0314     with_instance_map(ptr, [&](instance_map &instances) { instances.emplace(ptr, self); });
0315     return true; // unused, but gives the same signature as the deregister func
0316 }
0317 inline bool deregister_instance_impl(void *ptr, instance *self) {
0318     return with_instance_map(ptr, [&](instance_map &instances) {
0319         auto range = instances.equal_range(ptr);
0320         for (auto it = range.first; it != range.second; ++it) {
0321             if (self == it->second) {
0322                 instances.erase(it);
0323                 return true;
0324             }
0325         }
0326         return false;
0327     });
0328 }
0329 
0330 inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
0331     register_instance_impl(valptr, self);
0332     if (!tinfo->simple_ancestors) {
0333         traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
0334     }
0335 }
0336 
0337 inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
0338     bool ret = deregister_instance_impl(valptr, self);
0339     if (!tinfo->simple_ancestors) {
0340         traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
0341     }
0342     return ret;
0343 }
0344 
0345 /// Instance creation function for all pybind11 types. It allocates the internal instance layout
0346 /// for holding C++ objects and holders.  Allocation is done lazily (the first time the instance is
0347 /// cast to a reference or pointer), and initialization is done by an `__init__` function.
0348 inline PyObject *make_new_instance(PyTypeObject *type) {
0349 #if defined(PYPY_VERSION)
0350     // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
0351     // inherited object is a plain Python type (i.e. not derived from an extension type).  Fix it.
0352     ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
0353     if (type->tp_basicsize < instance_size) {
0354         type->tp_basicsize = instance_size;
0355     }
0356 #endif
0357     PyObject *self = type->tp_alloc(type, 0);
0358     auto *inst = reinterpret_cast<instance *>(self);
0359     // Allocate the value/holder internals:
0360     inst->allocate_layout();
0361 
0362     return self;
0363 }
0364 
0365 /// Instance creation function for all pybind11 types. It only allocates space for the
0366 /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
0367 extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
0368     return make_new_instance(type);
0369 }
0370 
0371 /// An `__init__` function constructs the C++ object. Users should provide at least one
0372 /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
0373 /// following default function will be used which simply throws an exception.
0374 extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
0375     PyTypeObject *type = Py_TYPE(self);
0376     std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
0377     set_error(PyExc_TypeError, msg.c_str());
0378     return -1;
0379 }
0380 
0381 inline void add_patient(PyObject *nurse, PyObject *patient) {
0382     auto *instance = reinterpret_cast<detail::instance *>(nurse);
0383     instance->has_patients = true;
0384     Py_INCREF(patient);
0385 
0386     with_internals([&](internals &internals) { internals.patients[nurse].push_back(patient); });
0387 }
0388 
0389 inline void clear_patients(PyObject *self) {
0390     auto *instance = reinterpret_cast<detail::instance *>(self);
0391     std::vector<PyObject *> patients;
0392 
0393     with_internals([&](internals &internals) {
0394         auto pos = internals.patients.find(self);
0395 
0396         if (pos == internals.patients.end()) {
0397             pybind11_fail(
0398                 "FATAL: Internal consistency check failed: Invalid clear_patients() call.");
0399         }
0400 
0401         // Clearing the patients can cause more Python code to run, which
0402         // can invalidate the iterator. Extract the vector of patients
0403         // from the unordered_map first.
0404         patients = std::move(pos->second);
0405         internals.patients.erase(pos);
0406     });
0407 
0408     instance->has_patients = false;
0409     for (PyObject *&patient : patients) {
0410         Py_CLEAR(patient);
0411     }
0412 }
0413 
0414 /// Clears all internal data from the instance and removes it from registered instances in
0415 /// preparation for deallocation.
0416 inline void clear_instance(PyObject *self) {
0417     auto *instance = reinterpret_cast<detail::instance *>(self);
0418 
0419     // Deallocate any values/holders, if present:
0420     for (auto &v_h : values_and_holders(instance)) {
0421         if (v_h) {
0422 
0423             // We have to deregister before we call dealloc because, for virtual MI types, we still
0424             // need to be able to get the parent pointers.
0425             if (v_h.instance_registered()
0426                 && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
0427                 pybind11_fail(
0428                     "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
0429             }
0430 
0431             if (instance->owned || v_h.holder_constructed()) {
0432                 v_h.type->dealloc(v_h);
0433             }
0434         }
0435     }
0436     // Deallocate the value/holder layout internals:
0437     instance->deallocate_layout();
0438 
0439     if (instance->weakrefs) {
0440         PyObject_ClearWeakRefs(self);
0441     }
0442 
0443     PyObject **dict_ptr = _PyObject_GetDictPtr(self);
0444     if (dict_ptr) {
0445         Py_CLEAR(*dict_ptr);
0446     }
0447 
0448     if (instance->has_patients) {
0449         clear_patients(self);
0450     }
0451 }
0452 
0453 /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
0454 /// to destroy the C++ object itself, while the rest is Python bookkeeping.
0455 extern "C" inline void pybind11_object_dealloc(PyObject *self) {
0456     auto *type = Py_TYPE(self);
0457 
0458     // If this is a GC tracked object, untrack it first
0459     // Note that the track call is implicitly done by the
0460     // default tp_alloc, which we never override.
0461     if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
0462         PyObject_GC_UnTrack(self);
0463     }
0464 
0465     clear_instance(self);
0466 
0467     type->tp_free(self);
0468 
0469 #if PY_VERSION_HEX < 0x03080000
0470     // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
0471     // as part of a derived type's dealloc, in which case we're not allowed to decref
0472     // the type here. For cross-module compatibility, we shouldn't compare directly
0473     // with `pybind11_object_dealloc`, but with the common one stashed in internals.
0474     auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
0475     if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
0476         Py_DECREF(type);
0477 #else
0478     // This was not needed before Python 3.8 (Python issue 35810)
0479     // https://github.com/pybind/pybind11/issues/1946
0480     Py_DECREF(type);
0481 #endif
0482 }
0483 
0484 std::string error_string();
0485 
0486 /** Create the type which can be used as a common base for all classes.  This is
0487     needed in order to satisfy Python's requirements for multiple inheritance.
0488     Return value: New reference. */
0489 inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
0490     constexpr auto *name = "pybind11_object";
0491     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
0492 
0493     /* Danger zone: from now (and until PyType_Ready), make sure to
0494        issue no Python C API calls which could potentially invoke the
0495        garbage collector (the GC will call type_traverse(), which will in
0496        turn find the newly constructed type in an invalid state) */
0497     auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
0498     if (!heap_type) {
0499         pybind11_fail("make_object_base_type(): error allocating type!");
0500     }
0501 
0502     heap_type->ht_name = name_obj.inc_ref().ptr();
0503 #ifdef PYBIND11_BUILTIN_QUALNAME
0504     heap_type->ht_qualname = name_obj.inc_ref().ptr();
0505 #endif
0506 
0507     auto *type = &heap_type->ht_type;
0508     type->tp_name = name;
0509     type->tp_base = type_incref(&PyBaseObject_Type);
0510     type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
0511     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
0512 
0513     type->tp_new = pybind11_object_new;
0514     type->tp_init = pybind11_object_init;
0515     type->tp_dealloc = pybind11_object_dealloc;
0516 
0517     /* Support weak references (needed for the keep_alive feature) */
0518     type->tp_weaklistoffset = offsetof(instance, weakrefs);
0519 
0520     if (PyType_Ready(type) < 0) {
0521         pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
0522     }
0523 
0524     setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
0525     PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
0526 
0527     assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
0528     return (PyObject *) heap_type;
0529 }
0530 
0531 /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
0532 extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
0533 #if PY_VERSION_HEX >= 0x030D0000
0534     PyObject_VisitManagedDict(self, visit, arg);
0535 #else
0536     PyObject *&dict = *_PyObject_GetDictPtr(self);
0537     Py_VISIT(dict);
0538 #endif
0539 // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
0540 #if PY_VERSION_HEX >= 0x03090000
0541     Py_VISIT(Py_TYPE(self));
0542 #endif
0543     return 0;
0544 }
0545 
0546 /// dynamic_attr: Allow the GC to clear the dictionary.
0547 extern "C" inline int pybind11_clear(PyObject *self) {
0548 #if PY_VERSION_HEX >= 0x030D0000
0549     PyObject_ClearManagedDict(self);
0550 #else
0551     PyObject *&dict = *_PyObject_GetDictPtr(self);
0552     Py_CLEAR(dict);
0553 #endif
0554     return 0;
0555 }
0556 
0557 /// Give instances of this type a `__dict__` and opt into garbage collection.
0558 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
0559     auto *type = &heap_type->ht_type;
0560     type->tp_flags |= Py_TPFLAGS_HAVE_GC;
0561 #if PY_VERSION_HEX < 0x030B0000
0562     type->tp_dictoffset = type->tp_basicsize;           // place dict at the end
0563     type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
0564 #else
0565     type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
0566 #endif
0567     type->tp_traverse = pybind11_traverse;
0568     type->tp_clear = pybind11_clear;
0569 
0570     static PyGetSetDef getset[]
0571         = {{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, nullptr, nullptr},
0572            {nullptr, nullptr, nullptr, nullptr, nullptr}};
0573     type->tp_getset = getset;
0574 }
0575 
0576 /// buffer_protocol: Fill in the view as specified by flags.
0577 extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
0578     // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
0579     type_info *tinfo = nullptr;
0580     for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
0581         tinfo = get_type_info((PyTypeObject *) type.ptr());
0582         if (tinfo && tinfo->get_buffer) {
0583             break;
0584         }
0585     }
0586     if (view == nullptr || !tinfo || !tinfo->get_buffer) {
0587         if (view) {
0588             view->obj = nullptr;
0589         }
0590         set_error(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
0591         return -1;
0592     }
0593     std::memset(view, 0, sizeof(Py_buffer));
0594     buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
0595     if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
0596         delete info;
0597         // view->obj = nullptr;  // Was just memset to 0, so not necessary
0598         set_error(PyExc_BufferError, "Writable buffer requested for readonly storage");
0599         return -1;
0600     }
0601     view->obj = obj;
0602     view->ndim = 1;
0603     view->internal = info;
0604     view->buf = info->ptr;
0605     view->itemsize = info->itemsize;
0606     view->len = view->itemsize;
0607     for (auto s : info->shape) {
0608         view->len *= s;
0609     }
0610     view->readonly = static_cast<int>(info->readonly);
0611     if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
0612         view->format = const_cast<char *>(info->format.c_str());
0613     }
0614     if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
0615         view->ndim = (int) info->ndim;
0616         view->strides = info->strides.data();
0617         view->shape = info->shape.data();
0618     }
0619     Py_INCREF(view->obj);
0620     return 0;
0621 }
0622 
0623 /// buffer_protocol: Release the resources of the buffer.
0624 extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
0625     delete (buffer_info *) view->internal;
0626 }
0627 
0628 /// Give this type a buffer interface.
0629 inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
0630     heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
0631 
0632     heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
0633     heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
0634 }
0635 
0636 /** Create a brand new Python type according to the `type_record` specification.
0637     Return value: New reference. */
0638 inline PyObject *make_new_python_type(const type_record &rec) {
0639     auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
0640 
0641     auto qualname = name;
0642     if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
0643         qualname = reinterpret_steal<object>(
0644             PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
0645     }
0646 
0647     object module_;
0648     if (rec.scope) {
0649         if (hasattr(rec.scope, "__module__")) {
0650             module_ = rec.scope.attr("__module__");
0651         } else if (hasattr(rec.scope, "__name__")) {
0652             module_ = rec.scope.attr("__name__");
0653         }
0654     }
0655 
0656     const auto *full_name = c_str(
0657 #if !defined(PYPY_VERSION)
0658         module_ ? str(module_).cast<std::string>() + "." + rec.name :
0659 #endif
0660                 rec.name);
0661 
0662     char *tp_doc = nullptr;
0663     if (rec.doc && options::show_user_defined_docstrings()) {
0664         /* Allocate memory for docstring (Python will free this later on) */
0665         size_t size = std::strlen(rec.doc) + 1;
0666 #if PY_VERSION_HEX >= 0x030D0000
0667         tp_doc = (char *) PyMem_MALLOC(size);
0668 #else
0669         tp_doc = (char *) PyObject_MALLOC(size);
0670 #endif
0671         std::memcpy((void *) tp_doc, rec.doc, size);
0672     }
0673 
0674     auto &internals = get_internals();
0675     auto bases = tuple(rec.bases);
0676     auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
0677 
0678     /* Danger zone: from now (and until PyType_Ready), make sure to
0679        issue no Python C API calls which could potentially invoke the
0680        garbage collector (the GC will call type_traverse(), which will in
0681        turn find the newly constructed type in an invalid state) */
0682     auto *metaclass
0683         = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
0684 
0685     auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
0686     if (!heap_type) {
0687         pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
0688     }
0689 
0690     heap_type->ht_name = name.release().ptr();
0691 #ifdef PYBIND11_BUILTIN_QUALNAME
0692     heap_type->ht_qualname = qualname.inc_ref().ptr();
0693 #endif
0694 
0695     auto *type = &heap_type->ht_type;
0696     type->tp_name = full_name;
0697     type->tp_doc = tp_doc;
0698     type->tp_base = type_incref((PyTypeObject *) base);
0699     type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
0700     if (!bases.empty()) {
0701         type->tp_bases = bases.release().ptr();
0702     }
0703 
0704     /* Don't inherit base __init__ */
0705     type->tp_init = pybind11_object_init;
0706 
0707     /* Supported protocols */
0708     type->tp_as_number = &heap_type->as_number;
0709     type->tp_as_sequence = &heap_type->as_sequence;
0710     type->tp_as_mapping = &heap_type->as_mapping;
0711     type->tp_as_async = &heap_type->as_async;
0712 
0713     /* Flags */
0714     type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
0715     if (!rec.is_final) {
0716         type->tp_flags |= Py_TPFLAGS_BASETYPE;
0717     }
0718 
0719     if (rec.dynamic_attr) {
0720         enable_dynamic_attributes(heap_type);
0721     }
0722 
0723     if (rec.buffer_protocol) {
0724         enable_buffer_protocol(heap_type);
0725     }
0726 
0727     if (rec.custom_type_setup_callback) {
0728         rec.custom_type_setup_callback(heap_type);
0729     }
0730 
0731     if (PyType_Ready(type) < 0) {
0732         pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
0733     }
0734 
0735     assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
0736 
0737     /* Register type with the parent scope */
0738     if (rec.scope) {
0739         setattr(rec.scope, rec.name, (PyObject *) type);
0740     } else {
0741         Py_INCREF(type); // Keep it alive forever (reference leak)
0742     }
0743 
0744     if (module_) { // Needed by pydoc
0745         setattr((PyObject *) type, "__module__", module_);
0746     }
0747 
0748     PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
0749 
0750     return (PyObject *) type;
0751 }
0752 
0753 PYBIND11_NAMESPACE_END(detail)
0754 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)