Skip to content

Commit 1a2b282

Browse files
authored
gh-89653: PEP 670: Convert PyWeakref_GET_OBJECT() to function (#91785)
Convert the PyWeakref_GET_OBJECT() macro to a static inline function. Add an assertion to check the argument with PyWeakref_Check(). Add a macro converting the argument to PyObject* to prevent emitting new compiler warning.
1 parent f2b4e45 commit 1a2b282

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

Include/cpython/weakrefobject.h

+16-10
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,19 @@ PyAPI_FUNC(Py_ssize_t) _PyWeakref_GetWeakrefCount(PyWeakReference *head);
3636

3737
PyAPI_FUNC(void) _PyWeakref_ClearRef(PyWeakReference *self);
3838

39-
/* Explanation for the Py_REFCNT() check: when a weakref's target is part
40-
of a long chain of deallocations which triggers the trashcan mechanism,
41-
clearing the weakrefs can be delayed long after the target's refcount
42-
has dropped to zero. In the meantime, code accessing the weakref will
43-
be able to "see" the target object even though it is supposed to be
44-
unreachable. See issue #16602. */
45-
#define PyWeakref_GET_OBJECT(ref) \
46-
(Py_REFCNT(((PyWeakReference *)(ref))->wr_object) > 0 \
47-
? ((PyWeakReference *)(ref))->wr_object \
48-
: Py_None)
39+
static inline PyObject* PyWeakref_GET_OBJECT(PyObject *ref_obj) {
40+
assert(PyWeakref_Check(ref_obj));
41+
PyWeakReference *ref = (PyWeakReference *)ref_obj;
42+
PyObject *obj = ref->wr_object;
43+
// Explanation for the Py_REFCNT() check: when a weakref's target is part
44+
// of a long chain of deallocations which triggers the trashcan mechanism,
45+
// clearing the weakrefs can be delayed long after the target's refcount
46+
// has dropped to zero. In the meantime, code accessing the weakref will
47+
// be able to "see" the target object even though it is supposed to be
48+
// unreachable. See issue gh-60806.
49+
if (Py_REFCNT(obj) > 0) {
50+
return obj;
51+
}
52+
return Py_None;
53+
}
54+
#define PyWeakref_GET_OBJECT(ref) PyWeakref_GET_OBJECT(_PyObject_CAST(ref))

0 commit comments

Comments
 (0)