bpo-28254: Add a C-API for controlling the GC state (GH-25687)
Add new C-API functions to control the state of the garbage collector:
PyGC_Enable(), PyGC_Disable(), PyGC_IsEnabled(),
corresponding to the functions in the gc module.
Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
diff --git a/Doc/c-api/gcsupport.rst b/Doc/c-api/gcsupport.rst
index eee114c..55ed9d4 100644
--- a/Doc/c-api/gcsupport.rst
+++ b/Doc/c-api/gcsupport.rst
@@ -173,3 +173,46 @@
this method (don't just call :c:func:`Py_DECREF` on a reference). The
collector will call this method if it detects that this object is involved
in a reference cycle.
+
+
+Controlling the Garbage Collector State
+---------------------------------------
+
+The C-API provides the following functions for controlling
+garbage collection runs.
+
+.. c:function:: Py_ssize_t PyGC_Collect(void)
+
+ Perform a full garbage collection, if the garbage collector is enabled.
+ (Note that :func:`gc.collect` runs it unconditionally.)
+
+ Returns the number of collected + unreachable objects which cannot
+ be collected.
+ If the garbage collector is disabled or already collecting,
+ returns ``0`` immediately.
+ Errors during garbage collection are passed to :data:`sys.unraisablehook`.
+ This function does not raise exceptions.
+
+
+.. c:function:: int PyGC_Enable(void)
+
+ Enable the garbage collector: similar to :func:`gc.enable`.
+ Returns the previous state, 0 for disabled and 1 for enabled.
+
+ .. versionadded:: 3.10
+
+
+.. c:function:: int PyGC_Disable(void)
+
+ Disable the garbage collector: similar to :func:`gc.disable`.
+ Returns the previous state, 0 for disabled and 1 for enabled.
+
+ .. versionadded:: 3.10
+
+
+.. c:function:: int PyGC_IsEnabled(void)
+
+ Query the state of the garbage collector: similar to :func:`gc.isenabled`.
+ Returns the current state, 0 for disabled and 1 for enabled.
+
+ .. versionadded:: 3.10
diff --git a/Doc/data/stable_abi.dat b/Doc/data/stable_abi.dat
index cdc7160..491a5fb 100644
--- a/Doc/data/stable_abi.dat
+++ b/Doc/data/stable_abi.dat
@@ -268,6 +268,9 @@
PyFrozenSet_New
PyFrozenSet_Type
PyGC_Collect
+PyGC_Disable
+PyGC_Enable
+PyGC_IsEnabled
PyGILState_Ensure
PyGILState_GetThisThreadState
PyGILState_Release
diff --git a/Doc/whatsnew/3.10.rst b/Doc/whatsnew/3.10.rst
index 2d8bb28..37c1b8a 100644
--- a/Doc/whatsnew/3.10.rst
+++ b/Doc/whatsnew/3.10.rst
@@ -1697,6 +1697,13 @@
singleton or the ``False`` singleton.
(Contributed by Victor Stinner in :issue:`43753`.)
+* Add new functions to quickly control the garbage collector from C code:
+ :c:func:`PyGC_Enable()`,
+ :c:func:`PyGC_Disable()`,
+ :c:func:`PyGC_IsEnabled()`.
+ These functions allow to activate, deactivate and query the state of the garbage collector from C code without
+ having to import the :mod:`gc` module.
+
Porting to Python 3.10
----------------------