Skip to content

Commit 8c5aeaa

Browse files
author
Jim Fulton
committed
Implemented a new Py_CLEAR macro. This macro should be used when
decrementing the refcount of variables that might be accessed as a result of calling Python
1 parent 7a0e8bc commit 8c5aeaa

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

Doc/api/refcounting.tex

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,22 @@ \chapter{Reference Counting \label{countingRefs}}
4242
applies.
4343
\end{cfuncdesc}
4444

45+
\begin{cfuncdesc}{void}{Py_CLEAR}{PyObject *o}
46+
Decrement the reference count for object \var{o}. The object may be
47+
\NULL, in which case the macro has no effect; otherwise the effect
48+
is the same as for \cfunction{Py_DECREF()}, except that the argument
49+
is also set to \NULL. The warning for \cfunction{Py_DECREF()}, does
50+
not apply with respect to the object passed because the macro
51+
carefully uses a temporary variable and sets the argument to \NULL
52+
before decrementing it's reference count.
53+
54+
It is a good idea to use this macro whenever decrementing the value
55+
of a variable that might be traversed during garbage collection.
56+
57+
\versionadded{2.4}
58+
\end{cfuncdesc}
59+
60+
4561
The following functions are for runtime dynamic embedding of Python:
4662
\cfunction{Py_IncRef(PyObject *o)}, \cfunction{Py_DecRef(PyObject *o)}.
4763
They are simply exported function versions of \cfunction{Py_XINCREF()} and

Include/object.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,15 @@ PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force);
620620
else \
621621
_Py_Dealloc((PyObject *)(op))
622622

623+
#define Py_CLEAR(op) \
624+
do { \
625+
if (op) { \
626+
PyObject *tmp = (op); \
627+
(op) = NULL; \
628+
Py_DECREF(tmp); \
629+
} \
630+
} while (0)
631+
623632
/* Macros to use in case the object pointer may be NULL: */
624633
#define Py_XINCREF(op) if ((op) == NULL) ; else Py_INCREF(op)
625634
#define Py_XDECREF(op) if ((op) == NULL) ; else Py_DECREF(op)

0 commit comments

Comments
 (0)