13#include "../options.h"
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) \
25 setattr((PyObject *) obj, "__qualname__", nameobj)
29#if !defined(PYPY_VERSION)
32 auto module_name =
handle((PyObject *)
type).attr(
"__module__").
cast<std::string>();
36 return std::move(module_name) +
"." +
type->tp_name;
45#if !defined(PYPY_VERSION)
49 return PyProperty_Type.tp_descr_get(
self, cls, cls);
54 PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
55 return PyProperty_Type.tp_descr_set(
self, cls, value);
62 constexpr auto *
name =
"pybind11_static_property";
69 auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
71 pybind11_fail(
"make_static_property_type(): error allocating type!");
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();
79 auto *
type = &heap_type->ht_type;
82 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
86 if (PyType_Ready(
type) < 0) {
87 pybind11_fail(
"make_static_property_type(): failure in PyType_Ready()!");
90 setattr((PyObject *)
type,
"__module__",
str(
"pybind11_builtins"));
103 PyObject *
result = PyRun_String(R
"(\
104class pybind11_static_property(property):
105 def __get__(self, obj, cls):
106 return property.__get__(self, cls, cls)
108 def __set__(self, obj, value):
109 cls = obj if isinstance(obj, type) else type(obj)
110 property.__set__(self, cls, value)
115 if (result ==
nullptr)
118 return (PyTypeObject *) d[
"pybind11_static_property"].cast<
object>().release().ptr();
130 PyObject *
descr = _PyType_Lookup((PyTypeObject *) obj,
name);
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) {
142#if !defined(PYPY_VERSION)
143 return Py_TYPE(
descr)->tp_descr_set(
descr, obj, value);
145 if (PyObject *result = PyObject_CallMethod(
descr,
"__set__",
"OO", obj, value)) {
154 return PyType_Type.tp_setattro(obj,
name, value);
158#if PY_MAJOR_VERSION >= 3
166 PyObject *
descr = _PyType_Lookup((PyTypeObject *) obj,
name);
171 return PyType_Type.tp_getattro(obj,
name);
180 if (
self ==
nullptr) {
185 auto *
instance =
reinterpret_cast<detail::instance *
>(
self);
189 if (!vh.holder_constructed()) {
190 PyErr_Format(PyExc_TypeError,
191 "%.200s.__init__() must be called when overriding __init__",
203 auto *
type = (PyTypeObject *) obj;
211 && found_type->second[0]->type ==
type) {
213 auto *tinfo = found_type->second[0];
214 auto tindex = std::type_index(*tinfo->cpptype);
217 if (tinfo->module_local) {
226 for (
auto it = cache.begin(),
last = cache.end(); it !=
last;) {
227 if (it->first == (PyObject *) tinfo->type) {
228 it = cache.erase(it);
237 PyType_Type.tp_dealloc(obj);
244 constexpr auto *
name =
"pybind11_type";
251 auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
253 pybind11_fail(
"make_default_metaclass(): error allocating metaclass!");
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();
261 auto *
type = &heap_type->ht_type;
264 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
269#if PY_MAJOR_VERSION >= 3
275 if (PyType_Ready(
type) < 0) {
276 pybind11_fail(
"make_default_metaclass(): failure in PyType_Ready()!");
279 setattr((PyObject *)
type,
"__module__",
str(
"pybind11_builtins"));
290 const detail::type_info *tinfo,
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) {
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);
344#if defined(PYPY_VERSION)
348 if (
type->tp_basicsize < instance_size) {
349 type->tp_basicsize = instance_size;
372 PyErr_SetString(PyExc_TypeError, msg.c_str());
378 auto *
instance =
reinterpret_cast<detail::instance *
>(nurse);
385 auto *
instance =
reinterpret_cast<detail::instance *
>(
self);
392 auto patients = std::move(pos->second);
395 for (PyObject *&patient : patients) {
403 auto *
instance =
reinterpret_cast<detail::instance *
>(
self);
411 if (v_h.instance_registered()
414 "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
418 v_h.type->dealloc(v_h);
426 PyObject_ClearWeakRefs(
self);
429 PyObject **dict_ptr = _PyObject_GetDictPtr(
self);
447#if PY_VERSION_HEX < 0x03080000
453 if (
type->tp_dealloc == pybind11_object_type->tp_dealloc)
466 constexpr auto *
name =
"pybind11_object";
475 pybind11_fail(
"make_object_base_type(): error allocating type!");
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();
483 auto *
type = &heap_type->ht_type;
487 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
496 if (PyType_Ready(
type) < 0) {
500 setattr((PyObject *)
type,
"__module__",
str(
"pybind11_builtins"));
503 assert(!PyType_HasFeature(
type, Py_TPFLAGS_HAVE_GC));
504 return (PyObject *) heap_type;
509 PyObject *&
dict = *_PyObject_GetDictPtr(
self);
519 if (!PyDict_Check(new_dict)) {
520 PyErr_Format(PyExc_TypeError,
521 "__dict__ must be set to a dictionary, not a '%.200s'",
525 PyObject *&
dict = *_PyObject_GetDictPtr(
self);
534 PyObject *&
dict = *_PyObject_GetDictPtr(
self);
541 PyObject *&
dict = *_PyObject_GetDictPtr(
self);
548 auto *
type = &heap_type->ht_type;
549 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
550 type->tp_dictoffset =
type->tp_basicsize;
551 type->tp_basicsize += (
ssize_t)
sizeof(PyObject *);
555 static PyGetSetDef getset[] = {
557 {
nullptr,
nullptr,
nullptr,
nullptr,
nullptr}};
558 type->tp_getset = getset;
565 for (
auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
571 if (view ==
nullptr || !tinfo || !tinfo->
get_buffer) {
575 PyErr_SetString(PyExc_BufferError,
"pybind11_getbuffer(): Internal error");
578 std::memset(view, 0,
sizeof(Py_buffer));
580 if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->
readonly) {
583 PyErr_SetString(PyExc_BufferError,
"Writable buffer requested for readonly storage");
588 view->internal = info;
589 view->buf = info->
ptr;
591 view->len = view->itemsize;
592 for (
auto s : info->
shape) {
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());
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();
604 Py_INCREF(view->obj);
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;
629 auto qualname =
name;
631#if PY_MAJOR_VERSION >= 3
632 qualname = reinterpret_steal<object>(
633 PyUnicode_FromFormat(
"%U.%U", rec.
scope.attr(
"__qualname__").
ptr(),
name.ptr()));
635 qualname =
str(rec.
scope.attr(
"__qualname__").
cast<std::string>() +
"." + rec.
name);
648 const auto *full_name =
c_str(
649#
if !defined(PYPY_VERSION)
654 char *tp_doc =
nullptr;
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);
679 heap_type->ht_name =
name.release().ptr();
680#ifdef PYBIND11_BUILTIN_QUALNAME
681 heap_type->ht_qualname = qualname.inc_ref().ptr();
684 auto *
type = &heap_type->ht_type;
685 type->tp_name = full_name;
686 type->tp_doc = tp_doc;
689 if (!bases.empty()) {
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;
705 type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
706#if PY_MAJOR_VERSION < 3
707 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
710 type->tp_flags |= Py_TPFLAGS_BASETYPE;
725 if (PyType_Ready(
type) < 0) {
744 return (PyObject *)
type;
Fetch and hold an error which was already set in Python.
\rst Holds a reference to a Python object (no reference counting)
T cast() const
\rst Attempt to cast the Python object into the given C++ type.
PyObject * ptr() const
Return the underlying PyObject * pointer.
Wrapper for Python extension modules.
handle release()
\rst Resets the internal pointer to nullptr without decreasing the object's reference count.
static bool show_user_defined_docstrings()
void setattr(handle obj, handle name, handle value)
bool hasattr(handle obj, handle name)
void enable_buffer_protocol(PyHeapTypeObject *heap_type)
Give this type a buffer interface.
PyObject * pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *)
Instance creation function for all pybind11 types.
PyTypeObject * make_default_metaclass()
This metaclass is assigned by default to all pybind11 types and is required in order for static prope...
PyObject * make_object_base_type(PyTypeObject *metaclass)
Create the type which can be used as a common base for all classes.
PyObject * pybind11_get_dict(PyObject *self, void *)
dynamic_attr: Support for d = instance.__dict__.
PyTypeObject * type_incref(PyTypeObject *type)
std::string get_fully_qualified_tp_name(PyTypeObject *type)
int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value)
pybind11_static_property.__set__(): Just like the above __get__().
int pybind11_object_init(PyObject *self, PyObject *, PyObject *)
An __init__ function constructs the C++ object.
void clear_patients(PyObject *self)
bool deregister_instance(instance *self, void *valptr, const type_info *tinfo)
void pybind11_releasebuffer(PyObject *, Py_buffer *view)
buffer_protocol: Release the resources of the buffer.
#define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
int pybind11_clear(PyObject *self)
dynamic_attr: Allow the GC to clear the dictionary.
void pybind11_object_dealloc(PyObject *self)
Instance destructor function for all pybind11 types.
void clear_instance(PyObject *self)
Clears all internal data from the instance and removes it from registered instances in preparation fo...
void register_instance(instance *self, void *valptr, const type_info *tinfo)
int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *)
dynamic_attr: Support for instance.__dict__ = dict().
void enable_dynamic_attributes(PyHeapTypeObject *heap_type)
Give instances of this type a __dict__ and opt into garbage collection.
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.
PyTypeObject * make_static_property_type()
A static_property is the same as a property but the __get__() and __set__() methods are modified to a...
int pybind11_traverse(PyObject *self, visitproc visit, void *arg)
dynamic_attr: Allow the garbage collector to traverse the internal instance __dict__.
bool deregister_instance_impl(void *ptr, instance *self)
PyObject * make_new_instance(PyTypeObject *type)
Instance creation function for all pybind11 types.
PyObject * make_new_python_type(const type_record &rec)
Create a brand new Python type according to the type_record specification.
bool register_instance_impl(void *ptr, instance *self)
void add_patient(PyObject *nurse, PyObject *patient)
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 ...
int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags)
buffer_protocol: Fill in the view as specified by flags.
void pybind11_meta_dealloc(PyObject *obj)
Cleanup the type-info for a pybind11-registered type.
PyObject * pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs)
metaclass __call__ function that is used to create all pybind11 objects.
PyObject * pybind11_static_get(PyObject *self, PyObject *, PyObject *cls)
pybind11_static_property.__get__(): Always pass the class instead of the instance.
constexpr int last(int, int result)
PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Thrown when pybind11::cast or.
#define PYBIND11_FROM_STRING
#define PYBIND11_BUILTINS_MODULE
#define PYBIND11_NAMESPACE_END(name)
#define PYBIND11_NAMESPACE_BEGIN(name)
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
const char * c_str(Args &&...args)
Constructs a std::string with the given arguments, stores it in internals, and returns its c_str().
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
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()
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...
Annotation for arguments.
Annotation indicating that a class derives from another given type.
Information record describing a Python buffer object.
std::vector< ssize_t > shape
std::vector< ssize_t > strides
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
void deallocate_layout()
Destroys/deallocates all of the above.
bool has_patients
If true, get_internals().patients has an entry for this object.
PyObject * weakrefs
Weak references.
bool owned
If true, the pointer is owned which means we're free to manage it with a holder.
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.
type_map< type_info * > registered_types_cpp
std::unordered_multimap< const void *, instance * > registered_instances
std::unordered_map< const PyObject *, std::vector< PyObject * > > patients
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
PyTypeObject * static_property_type
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
PyTypeObject * default_metaclass
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
type_map< type_info * > registered_types_cpp
Annotation for function names.
Additional type information which does not fit into the PyTypeObject.
buffer_info *(* get_buffer)(PyObject *, void *)
Special data structure which (temporarily) holds metadata about a bound class.
handle metaclass
Custom metaclass (optional)
const char * name
Name of the class.
bool is_final
Is the class inheritable from python classes?
handle scope
Handle to the parent scope.
bool buffer_protocol
Does the class implement the buffer protocol?
const char * doc
Optional docstring.
list bases
List of base classes of the newly created type.
custom_type_setup::callback custom_type_setup_callback
Custom type setup.
bool dynamic_attr
Does the class manage a dict?