Skip to content

Commit 6abb7de

Browse files
authored
chore: Use PyObject_GenericGetDict and PyObject_GenericSetDict functions (#4106)
* Try to update getset_dict APIs for 3.11 * Update API for all Python versions * Test ifdef for forward explicit forward compat * Fix ifdef
1 parent 8a4bca8 commit 6abb7de

File tree

1 file changed

+11
-28
lines changed

1 file changed

+11
-28
lines changed

include/pybind11/detail/class.h

Lines changed: 11 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -502,31 +502,6 @@ inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
502502
return (PyObject *) heap_type;
503503
}
504504

505-
/// dynamic_attr: Support for `d = instance.__dict__`.
506-
extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
507-
PyObject *&dict = *_PyObject_GetDictPtr(self);
508-
if (!dict) {
509-
dict = PyDict_New();
510-
}
511-
Py_XINCREF(dict);
512-
return dict;
513-
}
514-
515-
/// dynamic_attr: Support for `instance.__dict__ = dict()`.
516-
extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
517-
if (!PyDict_Check(new_dict)) {
518-
PyErr_Format(PyExc_TypeError,
519-
"__dict__ must be set to a dictionary, not a '%.200s'",
520-
get_fully_qualified_tp_name(Py_TYPE(new_dict)).c_str());
521-
return -1;
522-
}
523-
PyObject *&dict = *_PyObject_GetDictPtr(self);
524-
Py_INCREF(new_dict);
525-
Py_CLEAR(dict);
526-
dict = new_dict;
527-
return 0;
528-
}
529-
530505
/// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
531506
extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
532507
PyObject *&dict = *_PyObject_GetDictPtr(self);
@@ -558,9 +533,17 @@ inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
558533
type->tp_traverse = pybind11_traverse;
559534
type->tp_clear = pybind11_clear;
560535

561-
static PyGetSetDef getset[] = {
562-
{const_cast<char *>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
563-
{nullptr, nullptr, nullptr, nullptr, nullptr}};
536+
static PyGetSetDef getset[] = {{
537+
#if PY_VERSION_HEX < 0x03070000
538+
const_cast<char *>("__dict__"),
539+
#else
540+
"__dict__",
541+
#endif
542+
PyObject_GenericGetDict,
543+
PyObject_GenericSetDict,
544+
nullptr,
545+
nullptr},
546+
{nullptr, nullptr, nullptr, nullptr, nullptr}};
564547
type->tp_getset = getset;
565548
}
566549

0 commit comments

Comments
 (0)