[Patches] New sys method to return total reference count in debug builds.

Mark Hammond mhammond@skippinet.com.au
Mon, 5 Jun 2000 09:18:30 +1000


When recently tracking down leaks, I found the ability to see the total
number of Python references incredibly useful - it made it quite trivial to
see which functions were leaking Python object references.

This information is exposed in certain builds to the C API, but previously
wasn't exposed to Python.  This patch addresses this.  The function will be
exposed in default debug builds on the Windows platform, and any other
builds where Py_TRACE_REFS is defined.

Another slightly bogus reason for its inclusion is that interactive loops
written in Python could now truly mimic the C implemented interactive loop,
and print the total number of object references after each statement :-)

I decided to use the name 'gettotalrefcount', to be somewhat consistent
with the existing 'getrefcount'.  There is no docstring, as no other debug
only function appears to have one.

RCS file: /cvsroot/python/python/dist/src/Python/sysmodule.c,v
retrieving revision 2.63
diff -c -r2.63 sysmodule.c
*** sysmodule.c	2000/05/09 19:57:01	2.63
--- sysmodule.c	2000/06/04 23:12:17
***************
*** 268,273 ****
--- 268,285 ----
  	return PyInt_FromLong((long) arg->ob_refcnt);
  }

+ #ifdef Py_TRACE_REFS
+ static PyObject *
+ sys_gettotalrefcount(PyObject *self, PyObject *args)
+ {
+ 	extern long _Py_RefTotal;
+ 	if (!PyArg_ParseTuple(args, ":gettotalrefcount"))
+ 		return NULL;
+ 	return PyInt_FromLong((long) _Py_RefTotal);
+ }
+
+ #endif /* Py_TRACE_REFS */
+
  static char getrefcount_doc[] =
  "getrefcount(object) -> integer\n\
  \n\
***************
*** 310,315 ****
--- 322,328 ----
  #endif
  #ifdef Py_TRACE_REFS
  	{"getobjects",	_Py_GetObjects, 1},
+ 	{"gettotalrefcount", sys_gettotalrefcount, 1},
  #endif
  	{"getrefcount",	sys_getrefcount, 1, getrefcount_doc},
  #ifdef USE_MALLOPT

Release info:

I confirm that, to the best of my knowledge and belief, this contribution
is free of any claims of third parties under copyright, patent or other
rights or interests ("claims").  To the extent that I have any such claims,
I hereby grant to CNRI a nonexclusive, irrevocable, royalty-free, worldwide
license to reproduce, distribute, perform and/or display publicly, prepare
derivative versions, and otherwise use this contribution as part of the
Python software and its related documentation, or any derivative versions
thereof, at no cost to CNRI or its licensed users, and to authorize others
to do so.

I acknowledge that CNRI may, at its sole discretion, decide whether or not
to incorporate this contribution in the Python software and its related
documentation.  I further grant CNRI permission to use my name and other
identifying information provided to CNRI by me for use in connection with
the Python software and its related documentation.

Mark.