Skip to content

Commit 6bb37a5

Browse files
committed
refactor: use named flag for explicit weakref lists
Rather than checking the Python version repeatedly. See: https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_weaklistoffset
1 parent 25d664a commit 6bb37a5

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

src/zope/interface/_zope_interface_coptimizations.c

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,14 @@
4949
#define USE_HEAP_TYPES 1
5050
#endif
5151

52-
/* Add MANAGED_WEAKREF flag for Python >= 3.12 */
5352
#if PY_VERSION_HEX >= 0x030c0000
53+
/* Add MANAGED_WEAKREF flag for Python >= 3.12, and don't define
54+
* the '.tp_weaklistoffset' slot.
55+
*
56+
* See: https://docs.python.org/3/c-api/typeobj.html
57+
* #c.PyTypeObject.tp_weaklistoffset
58+
*/
59+
#define USE_EXPLICIT_WEAKREFLIST 0
5460
#define LEAFTYPE_FLAGS \
5561
Py_TPFLAGS_DEFAULT | \
5662
Py_TPFLAGS_MANAGED_WEAKREF | \
@@ -61,6 +67,13 @@
6167
Py_TPFLAGS_MANAGED_WEAKREF | \
6268
Py_TPFLAGS_HAVE_GC
6369
#else
70+
/* No MANAGED_WEAKREF flag for Python < 3.12, and therefore define
71+
* the '.tp_weaklistoffset' slot, and the member whose offset it holds.
72+
*
73+
* See: https://docs.python.org/3/c-api/typeobj.html
74+
* #c.PyTypeObject.tp_weaklistoffset
75+
*/
76+
#define USE_EXPLICIT_WEAKREFLIST 1
6477
#define LEAFTYPE_FLAGS \
6578
Py_TPFLAGS_DEFAULT | \
6679
Py_TPFLAGS_HAVE_GC
@@ -217,7 +230,7 @@ typedef struct
217230
make any assumptions about contents.
218231
*/
219232
PyObject* _implied;
220-
#if PY_VERSION_HEX < 0x030c0000
233+
#if USE_EXPLICIT_WEAKREFLIST
221234
PyObject* weakreflist;
222235
#endif
223236
/*
@@ -271,7 +284,7 @@ SB_dealloc(SB* self)
271284
{
272285
PyObject_GC_UnTrack((PyObject*)self);
273286
PyTypeObject* tp = Py_TYPE(self);
274-
#if PY_VERSION_HEX < 0x030c0000
287+
#if USE_EXPLICIT_WEAKREFLIST
275288
if (self->weakreflist != NULL) {
276289
PyObject_ClearWeakRefs(OBJECT(self));
277290
}
@@ -393,7 +406,7 @@ static PyMemberDef SB_members[] = {
393406
{ "_v_attrs", T_OBJECT_EX, offsetof(SB, _v_attrs), 0, "" },
394407
{ "__iro__", T_OBJECT_EX, offsetof(SB, __iro__), 0, "" },
395408
{ "__sro__", T_OBJECT_EX, offsetof(SB, __sro__), 0, "" },
396-
#if PY_VERSION_HEX < 0x030c0000
409+
#if USE_EXPLICIT_WEAKREFLIST
397410
{ "__weaklistoffset__", T_OBJECT_EX, offsetof(SB, weakreflist), 0, "" },
398411
#endif
399412
{ NULL },
@@ -418,7 +431,9 @@ static PyTypeObject SB_type_def = {
418431
.tp_traverse = (traverseproc)SB_traverse,
419432
.tp_clear = (inquiry)SB_clear,
420433
.tp_dealloc = (destructor)SB_dealloc,
421-
.tp_weaklistoffset = offsetof(SB, weakreflist), /* XXX */
434+
#if USE_EXPLICIT_WEAKREFLIST
435+
.tp_weaklistoffset = offsetof(SB, weakreflist),
436+
#endif
422437
.tp_methods = SB_methods,
423438
.tp_members = SB_members,
424439
};

0 commit comments

Comments
 (0)