13 #include "../options.h"
15 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16 PYBIND11_NAMESPACE_BEGIN(detail)
18 #if PY_VERSION_HEX >= 0x03030000 && !defined(PYPY_VERSION)
19 # define PYBIND11_BUILTIN_QUALNAME
20 # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
24 # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) setattr((PyObject *) obj, "__qualname__", nameobj)
27 inline std::string get_fully_qualified_tp_name(PyTypeObject *
type) {
28 #if !defined(PYPY_VERSION)
31 auto module_name =
handle((PyObject *) type).attr(
"__module__").
cast<std::string>();
32 if (module_name == PYBIND11_BUILTINS_MODULE)
35 return std::move(module_name) +
"." + type->tp_name;
39 inline PyTypeObject *type_incref(PyTypeObject *type) {
44 #if !defined(PYPY_VERSION)
47 extern "C" inline PyObject *pybind11_static_get(PyObject *
self, PyObject * , PyObject *cls) {
48 return PyProperty_Type.tp_descr_get(
self, cls, cls);
52 extern "C" inline int pybind11_static_set(PyObject *
self, PyObject *obj, PyObject *value) {
53 PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
54 return PyProperty_Type.tp_descr_set(
self, cls, value);
60 inline PyTypeObject *make_static_property_type() {
61 constexpr
auto *
name =
"pybind11_static_property";
62 auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
68 auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
70 pybind11_fail(
"make_static_property_type(): error allocating type!");
72 heap_type->ht_name = name_obj.inc_ref().ptr();
73 #ifdef PYBIND11_BUILTIN_QUALNAME
74 heap_type->ht_qualname = name_obj.inc_ref().ptr();
77 auto type = &heap_type->ht_type;
79 type->tp_base = type_incref(&PyProperty_Type);
80 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
81 type->tp_descr_get = pybind11_static_get;
82 type->tp_descr_set = pybind11_static_set;
84 if (PyType_Ready(type) < 0)
85 pybind11_fail(
"make_static_property_type(): failure in PyType_Ready()!");
87 setattr((PyObject *) type,
"__module__",
str(
"pybind11_builtins"));
88 PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
98 inline PyTypeObject *make_static_property_type() {
100 PyObject *result = PyRun_String(R
"(\
class pybind11_static_property(property):
def __get__(self, obj, cls):
return property.__get__(self, cls, cls)
def __set__(self, obj, value):
cls = obj if isinstance(obj, type) else type(obj)
property.__set__(self, cls, value)
)", Py_file_input, d.ptr(), d.ptr()
102 if (result ==
nullptr)
105 return (PyTypeObject *) d[
"pybind11_static_property"].cast<
object>().release().ptr();
114 extern "C" inline int pybind11_meta_setattro(PyObject* obj, PyObject* name, PyObject* value) {
117 PyObject *
descr = _PyType_Lookup((PyTypeObject *) obj, name);
123 const auto static_prop = (PyObject *) get_internals().static_property_type;
124 const auto call_descr_set = descr && PyObject_IsInstance(descr, static_prop)
125 && !PyObject_IsInstance(value, static_prop);
126 if (call_descr_set) {
128 #if !defined(PYPY_VERSION)
129 return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
131 if (PyObject *result = PyObject_CallMethod(descr,
"__set__",
"OO", obj, value)) {
140 return PyType_Type.tp_setattro(obj, name, value);
144 #if PY_MAJOR_VERSION >= 3
151 extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
152 PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
153 if (descr && PyInstanceMethod_Check(descr)) {
158 return PyType_Type.tp_getattro(obj, name);
164 extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *
args, PyObject *
kwargs) {
167 PyObject *
self = PyType_Type.tp_call(type, args, kwargs);
168 if (
self ==
nullptr) {
173 auto instance =
reinterpret_cast<detail::instance *
>(
self);
177 if (!vh.holder_constructed()) {
178 PyErr_Format(PyExc_TypeError,
"%.200s.__init__() must be called when overriding __init__",
179 get_fully_qualified_tp_name(vh.type->type).c_str());
189 extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
190 auto *type = (PyTypeObject *) obj;
196 auto found_type =
internals.registered_types_py.find(type);
197 if (found_type !=
internals.registered_types_py.end() &&
198 found_type->second.size() == 1 &&
199 found_type->second[0]->type == type) {
201 auto *tinfo = found_type->second[0];
202 auto tindex = std::type_index(*tinfo->cpptype);
203 internals.direct_conversions.erase(tindex);
205 if (tinfo->module_local)
206 registered_local_types_cpp().erase(tindex);
208 internals.registered_types_cpp.erase(tindex);
209 internals.registered_types_py.erase(tinfo->type);
212 auto &cache =
internals.inactive_override_cache;
213 for (
auto it = cache.begin(), last = cache.end(); it != last; ) {
214 if (it->first == (PyObject *) tinfo->type)
215 it = cache.erase(it);
223 PyType_Type.tp_dealloc(obj);
229 inline PyTypeObject* make_default_metaclass() {
230 constexpr
auto *name =
"pybind11_type";
231 auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
237 auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
239 pybind11_fail(
"make_default_metaclass(): error allocating metaclass!");
241 heap_type->ht_name = name_obj.inc_ref().ptr();
242 #ifdef PYBIND11_BUILTIN_QUALNAME
243 heap_type->ht_qualname = name_obj.inc_ref().ptr();
246 auto type = &heap_type->ht_type;
247 type->tp_name = name;
248 type->tp_base = type_incref(&PyType_Type);
249 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
251 type->tp_call = pybind11_meta_call;
253 type->tp_setattro = pybind11_meta_setattro;
254 #if PY_MAJOR_VERSION >= 3
255 type->tp_getattro = pybind11_meta_getattro;
258 type->tp_dealloc = pybind11_meta_dealloc;
260 if (PyType_Ready(type) < 0)
261 pybind11_fail(
"make_default_metaclass(): failure in PyType_Ready()!");
263 setattr((PyObject *) type,
"__module__",
str(
"pybind11_builtins"));
264 PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
272 inline void traverse_offset_bases(
void *valueptr,
const detail::type_info *tinfo,
instance *
self,
274 for (
handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
275 if (
auto parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
276 for (
auto &c : parent_tinfo->implicit_casts) {
277 if (c.first == tinfo->cpptype) {
278 auto *parentptr = c.second(valueptr);
279 if (parentptr != valueptr)
281 traverse_offset_bases(parentptr, parent_tinfo,
self, f);
289 inline bool register_instance_impl(
void *ptr,
instance *
self) {
290 get_internals().registered_instances.emplace(ptr,
self);
293 inline bool deregister_instance_impl(
void *ptr,
instance *
self) {
294 auto ®istered_instances = get_internals().registered_instances;
295 auto range = registered_instances.equal_range(ptr);
296 for (
auto it = range.first; it != range.second; ++it) {
297 if (
self == it->second) {
298 registered_instances.erase(it);
305 inline void register_instance(
instance *
self,
void *valptr,
const type_info *tinfo) {
306 register_instance_impl(valptr,
self);
307 if (!tinfo->simple_ancestors)
308 traverse_offset_bases(valptr, tinfo,
self, register_instance_impl);
311 inline bool deregister_instance(
instance *
self,
void *valptr,
const type_info *tinfo) {
312 bool ret = deregister_instance_impl(valptr,
self);
313 if (!tinfo->simple_ancestors)
314 traverse_offset_bases(valptr, tinfo,
self, deregister_instance_impl);
321 inline PyObject *make_new_instance(PyTypeObject *type) {
322 #if defined(PYPY_VERSION)
325 ssize_t instance_size =
static_cast<ssize_t
>(
sizeof(
instance));
326 if (type->tp_basicsize < instance_size) {
327 type->tp_basicsize = instance_size;
330 PyObject *
self = type->tp_alloc(type, 0);
331 auto inst =
reinterpret_cast<instance *
>(
self);
342 extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
343 return make_new_instance(type);
349 extern "C" inline int pybind11_object_init(PyObject *
self, PyObject *, PyObject *) {
350 PyTypeObject *type = Py_TYPE(
self);
351 std::string msg = get_fully_qualified_tp_name(type) +
": No constructor defined!";
352 PyErr_SetString(PyExc_TypeError, msg.c_str());
356 inline void add_patient(PyObject *nurse, PyObject *patient) {
358 auto instance =
reinterpret_cast<detail::instance *
>(nurse);
361 internals.patients[nurse].push_back(patient);
364 inline void clear_patients(PyObject *
self) {
365 auto instance =
reinterpret_cast<detail::instance *
>(
self);
367 auto pos =
internals.patients.find(
self);
372 auto patients = std::move(pos->second);
375 for (PyObject *&patient : patients)
381 inline void clear_instance(PyObject *
self) {
382 auto instance =
reinterpret_cast<detail::instance *
>(
self);
390 if (v_h.instance_registered() && !deregister_instance(
instance, v_h.value_ptr(), v_h.type))
391 pybind11_fail(
"pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
394 v_h.type->dealloc(v_h);
401 PyObject_ClearWeakRefs(
self);
403 PyObject **dict_ptr = _PyObject_GetDictPtr(
self);
408 clear_patients(
self);
413 extern "C" inline void pybind11_object_dealloc(PyObject *
self) {
414 clear_instance(
self);
416 auto type = Py_TYPE(
self);
419 #if PY_VERSION_HEX < 0x03080000
424 auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
425 if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
437 inline PyObject *make_object_base_type(PyTypeObject *
metaclass) {
438 constexpr
auto *name =
"pybind11_object";
439 auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
445 auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
447 pybind11_fail(
"make_object_base_type(): error allocating type!");
449 heap_type->ht_name = name_obj.inc_ref().ptr();
450 #ifdef PYBIND11_BUILTIN_QUALNAME
451 heap_type->ht_qualname = name_obj.inc_ref().ptr();
454 auto type = &heap_type->ht_type;
455 type->tp_name = name;
456 type->tp_base = type_incref(&PyBaseObject_Type);
457 type->tp_basicsize =
static_cast<ssize_t
>(
sizeof(
instance));
458 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
460 type->tp_new = pybind11_object_new;
461 type->tp_init = pybind11_object_init;
462 type->tp_dealloc = pybind11_object_dealloc;
465 type->tp_weaklistoffset = offsetof(
instance, weakrefs);
467 if (PyType_Ready(type) < 0)
468 pybind11_fail(
"PyType_Ready failed in make_object_base_type():" + error_string());
470 setattr((PyObject *) type,
"__module__",
str(
"pybind11_builtins"));
471 PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
473 assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
474 return (PyObject *) heap_type;
478 extern "C" inline PyObject *pybind11_get_dict(PyObject *
self,
void *) {
479 PyObject *&
dict = *_PyObject_GetDictPtr(
self);
487 extern "C" inline int pybind11_set_dict(PyObject *
self, PyObject *new_dict,
void *) {
488 if (!PyDict_Check(new_dict)) {
489 PyErr_Format(PyExc_TypeError,
"__dict__ must be set to a dictionary, not a '%.200s'",
490 get_fully_qualified_tp_name(Py_TYPE(new_dict)).c_str());
493 PyObject *&dict = *_PyObject_GetDictPtr(
self);
501 extern "C" inline int pybind11_traverse(PyObject *
self, visitproc visit,
void *arg) {
502 PyObject *&dict = *_PyObject_GetDictPtr(
self);
508 extern "C" inline int pybind11_clear(PyObject *
self) {
509 PyObject *&dict = *_PyObject_GetDictPtr(
self);
515 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
516 auto type = &heap_type->ht_type;
517 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
518 type->tp_dictoffset = type->tp_basicsize;
519 type->tp_basicsize += (ssize_t)
sizeof(PyObject *);
520 type->tp_traverse = pybind11_traverse;
521 type->tp_clear = pybind11_clear;
523 static PyGetSetDef getset[] = {
524 {
const_cast<char*
>(
"__dict__"), pybind11_get_dict, pybind11_set_dict,
nullptr,
nullptr},
525 {
nullptr,
nullptr,
nullptr,
nullptr,
nullptr}
527 type->tp_getset = getset;
531 extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view,
int flags) {
534 for (
auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
535 tinfo = get_type_info((PyTypeObject *) type.ptr());
536 if (tinfo && tinfo->get_buffer)
539 if (view ==
nullptr || !tinfo || !tinfo->get_buffer) {
542 PyErr_SetString(PyExc_BufferError,
"pybind11_getbuffer(): Internal error");
545 std::memset(view, 0,
sizeof(Py_buffer));
546 buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
549 view->internal = info;
550 view->buf = info->ptr;
551 view->itemsize = info->itemsize;
552 view->len = view->itemsize;
553 for (
auto s : info->shape)
555 view->readonly = info->readonly;
556 if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
559 PyErr_SetString(PyExc_BufferError,
"Writable buffer requested for readonly storage");
562 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
563 view->format =
const_cast<char *
>(info->format.c_str());
564 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
565 view->ndim = (int) info->ndim;
566 view->strides = &info->strides[0];
567 view->shape = &info->shape[0];
569 Py_INCREF(view->obj);
574 extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
579 inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
580 heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
581 #if PY_MAJOR_VERSION < 3
582 heap_type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
585 heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
586 heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
591 inline PyObject* make_new_python_type(
const type_record &rec) {
592 auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.
name));
594 auto qualname = name;
595 if (rec.
scope && !PyModule_Check(rec.
scope.
ptr()) && hasattr(rec.
scope,
"__qualname__")) {
596 #if PY_MAJOR_VERSION >= 3
597 qualname = reinterpret_steal<object>(
598 PyUnicode_FromFormat(
"%U.%U", rec.
scope.attr(
"__qualname__").
ptr(), name.ptr()));
600 qualname =
str(rec.
scope.attr(
"__qualname__").
cast<std::string>() +
"." + rec.
name);
606 if (hasattr(rec.
scope,
"__module__"))
607 module_ = rec.
scope.attr(
"__module__");
608 else if (hasattr(rec.
scope,
"__name__"))
609 module_ = rec.
scope.attr(
"__name__");
612 auto full_name = c_str(
613 #
if !defined(PYPY_VERSION)
614 module_ ?
str(module_).cast<std::string>() +
"." + rec.
name :
618 char *tp_doc =
nullptr;
619 if (rec.
doc && options::show_user_defined_docstrings()) {
622 size_t size = strlen(rec.
doc) + 1;
623 tp_doc = (
char *) PyObject_MALLOC(size);
624 memcpy((
void *) tp_doc, rec.
doc, size);
639 auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
641 pybind11_fail(std::string(rec.
name) +
": Unable to create type object!");
643 heap_type->ht_name = name.release().ptr();
644 #ifdef PYBIND11_BUILTIN_QUALNAME
645 heap_type->ht_qualname = qualname.inc_ref().ptr();
648 auto type = &heap_type->ht_type;
649 type->tp_name = full_name;
650 type->tp_doc = tp_doc;
651 type->tp_base = type_incref((PyTypeObject *)
base);
652 type->tp_basicsize =
static_cast<ssize_t
>(
sizeof(
instance));
654 type->tp_bases = bases.release().ptr();
657 type->tp_init = pybind11_object_init;
660 type->tp_as_number = &heap_type->as_number;
661 type->tp_as_sequence = &heap_type->as_sequence;
662 type->tp_as_mapping = &heap_type->as_mapping;
663 #if PY_VERSION_HEX >= 0x03050000
664 type->tp_as_async = &heap_type->as_async;
668 type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
669 #if PY_MAJOR_VERSION < 3
670 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
673 type->tp_flags |= Py_TPFLAGS_BASETYPE;
676 enable_dynamic_attributes(heap_type);
679 enable_buffer_protocol(heap_type);
681 if (PyType_Ready(type) < 0)
682 pybind11_fail(std::string(rec.
name) +
": PyType_Ready failed (" + error_string() +
")!");
684 assert(rec.
dynamic_attr ? PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC)
685 : !PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
689 setattr(rec.
scope, rec.
name, (PyObject *) type);
694 setattr((PyObject *) type,
"__module__", module_);
696 PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
698 return (PyObject *) type;
701 PYBIND11_NAMESPACE_END(detail)
702 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
703 list bases
List of base classes of the newly created type.
bool dynamic_attr
Does the class manage a dict?
Wrapper for Python extension modules.
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof') ...
void allocate_layout()
Initializes all of the above type/values/holders data (but not the instance values themselves) ...
PyObject * ptr() const
Return the underlying PyObject * pointer.
const char * doc
Optional docstring.
const char * name
Name of the class.
bool has_patients
If true, get_internals().patients has an entry for this object.
Special data structure which (temporarily) holds metadata about a bound class.
bool is_final
Is the class inheritable from python classes?
handle metaclass
Custom metaclass (optional)
void deallocate_layout()
Destroys/deallocates all of the above.
Annotation for function names.
Annotation indicating that a class derives from another given type.
Information record describing a Python buffer object.
bool buffer_protocol
Does the class implement the buffer protocol?
handle scope
Handle to the parent scope.
bool owned
If true, the pointer is owned which means we're free to manage it with a holder.
PyObject * weakrefs
Weak references.