Skip to content

Commit 3c082a7

Browse files
authored
bpo-31733: Add PYTHONSHOWREFCOUNT env var (GH-3932)
Add a new PYTHONSHOWREFCOUNT environment variable. In debug mode, Python now only print the total reference count if PYTHONSHOWREFCOUNT is set.
1 parent 50cef52 commit 3c082a7

File tree

3 files changed

+26
-10
lines changed

3 files changed

+26
-10
lines changed

Doc/using/cmdline.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -663,3 +663,10 @@ if Python was configured with the ``--with-pydebug`` build option.
663663

664664
If set, Python will print memory allocation statistics every time a new
665665
object arena is created, and on shutdown.
666+
667+
.. envvar:: PYTHONSHOWREFCOUNT
668+
669+
If set, Python will print the total reference count when the program
670+
finishes or after each statement in the interactive interpreter.
671+
672+
.. versionadded:: 2.7.15
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Add a new PYTHONSHOWREFCOUNT environment variable. In debug mode, Python now
2+
only print the total reference count if PYTHONSHOWREFCOUNT is set.

Python/pythonrun.c

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,6 @@
3737
#include "windows.h"
3838
#endif
3939

40-
#ifndef Py_REF_DEBUG
41-
#define PRINT_TOTAL_REFS()
42-
#else /* Py_REF_DEBUG */
43-
#define PRINT_TOTAL_REFS() fprintf(stderr, \
44-
"[%" PY_FORMAT_SIZE_T "d refs]\n", \
45-
_Py_GetRefTotal())
46-
#endif
47-
4840
#ifdef __cplusplus
4941
extern "C" {
5042
#endif
@@ -104,6 +96,21 @@ PyModule_GetWarningsModule(void)
10496
return PyImport_ImportModule("warnings");
10597
}
10698

99+
static void
100+
_PyDebug_PrintTotalRefs(void)
101+
{
102+
#ifdef Py_REF_DEBUG
103+
Py_ssize_t total;
104+
105+
if (!Py_GETENV("PYTHONSHOWREFCOUNT")) {
106+
return;
107+
}
108+
109+
total = _Py_GetRefTotal();
110+
fprintf(stderr, "[%" PY_FORMAT_SIZE_T "d refs]\n", total);
111+
#endif
112+
}
113+
107114
static int initialized = 0;
108115

109116
/* API to access the initialized flag -- useful for esoteric use */
@@ -484,7 +491,7 @@ Py_Finalize(void)
484491
dump_counts(stdout);
485492
#endif
486493

487-
PRINT_TOTAL_REFS();
494+
_PyDebug_PrintTotalRefs();
488495

489496
#ifdef Py_TRACE_REFS
490497
/* Display all objects still alive -- this can invoke arbitrary
@@ -775,7 +782,7 @@ PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flag
775782
}
776783
for (;;) {
777784
ret = PyRun_InteractiveOneFlags(fp, filename, flags);
778-
PRINT_TOTAL_REFS();
785+
_PyDebug_PrintTotalRefs();
779786
if (ret == E_EOF)
780787
return 0;
781788
/*

0 commit comments

Comments
 (0)