+ `;
+
+ this.container.appendChild(panel);
+
+ this.playPauseBtn = panel.querySelector("#play-pause-btn");
+ this.resetBtn = panel.querySelector("#reset-btn");
+ this.stepBtn = panel.querySelector("#step-btn");
+ this.scrubber = panel.querySelector("#timeline-scrubber");
+ this.timeDisplay = panel.querySelector("#time-display");
+
+ this.playPauseBtn.addEventListener("click", () =>
+ this._togglePlayPause(),
+ );
+ this.resetBtn.addEventListener("click", () => this._handleReset());
+ this.stepBtn.addEventListener("click", () => this._handleStep());
+ this.scrubber.addEventListener("input", (e) => this._handleSeek(e));
+
+ if (this.onSampleIntervalChange) {
+ this.sampleIntervalSlider = panel.querySelector("#sample-interval");
+ this.intervalDisplay = panel.querySelector("#interval-display");
+ this.sampleIntervalSlider.addEventListener("input", (e) =>
+ this._handleSampleIntervalChange(e),
+ );
+ }
+ }
+
+ _handleSampleIntervalChange(e) {
+ const interval = parseInt(e.target.value);
+ this.intervalDisplay.textContent = `${interval}ms`;
+ this.onSampleIntervalChange(interval);
+ }
+
+ _togglePlayPause() {
+ this.isPlaying = !this.isPlaying;
+
+ if (this.isPlaying) {
+ this.playPauseBtn.textContent = "โธ Pause";
+ this.playPauseBtn.classList.add("active");
+ this.onPlay();
+ } else {
+ this.playPauseBtn.textContent = "โถ Play";
+ this.playPauseBtn.classList.remove("active");
+ this.onPause();
+ }
+ }
+
+ _handleReset() {
+ this.isPlaying = false;
+ this.playPauseBtn.textContent = "โถ Play";
+ this.playPauseBtn.classList.remove("active");
+ this.scrubber.value = 0;
+ this.timeDisplay.textContent = "0ms";
+ this.onReset();
+ }
+
+ _handleStep() {
+ if (this.onStep) this.onStep();
+ }
+
+ _handleSeek(e) {
+ const percentage = parseFloat(e.target.value);
+ this.onSeek(percentage / 100);
+ }
+
+ updateTimeDisplay(currentTime, totalTime) {
+ this.timeDisplay.textContent = `${Math.floor(currentTime)}ms / ${Math.floor(totalTime)}ms`;
+ const percentage = (currentTime / totalTime) * 100;
+ this.scrubber.value = percentage;
+ }
+
+ setDuration(duration) {
+ this.duration = duration;
+ }
+
+ pause() {
+ if (this.isPlaying) this._togglePlayPause();
+ }
+
+ destroy() {
+ const panel = this.container.querySelector("#control-panel");
+ if (panel) panel.remove();
+ }
+ }
+
+ // ============================================================================
+ // Visual Effects Manager
+ // ============================================================================
+
+ class VisualEffectsManager {
+ constructor(container) {
+ this.container = container;
+ this.flyingAnimationInProgress = false;
+
+ this.flashOverlay = document.createElement("div");
+ this.flashOverlay.className = "flash-overlay";
+ this.container.appendChild(this.flashOverlay);
+ }
+
+ triggerSamplingEffect(stackViz, samplingPanel, currentTime, trace) {
+ if (this.flyingAnimationInProgress) return;
+
+ const stack = trace.getStackAt(currentTime);
+
+ if (stack.length === 0) {
+ samplingPanel.addSample(stack);
+ return;
+ }
+
+ this.flyingAnimationInProgress = true;
+ stackViz.flashAll();
+
+ const clone = stackViz.createStackClone(this.container);
+ const targetPosition = samplingPanel.getTargetPosition();
+
+ this._animateFlash();
+ this._animateFlyingStack(clone, targetPosition, () => {
+ samplingPanel.showImpactEffect(targetPosition);
+ clone.remove();
+
+ const currentStack = trace.getStackAt(currentTime);
+ samplingPanel.addSample(currentStack);
+ this.flyingAnimationInProgress = false;
+ });
+ }
+
+ _animateFlash() {
+ anim.to(this.flashOverlay, { opacity: 0.1 }, 0).onfinish = () => {
+ anim.to(this.flashOverlay, { opacity: 0 }, 150, "easeOutQuad");
+ };
+ }
+
+ _animateFlyingStack(clone, targetPosition, onComplete) {
+ const containerRect = this.container.getBoundingClientRect();
+ const cloneRect = clone.getBoundingClientRect();
+
+ // Convert viewport coordinates to container-relative
+ const startX = cloneRect.left - containerRect.left + cloneRect.width / 2;
+ const startY = cloneRect.top - containerRect.top + cloneRect.height / 2;
+ const targetX = targetPosition.x - containerRect.left;
+ const targetY = targetPosition.y - containerRect.top;
+
+ const deltaX = targetX - startX;
+ const deltaY = targetY - startY;
+
+ anim.to(
+ clone,
+ {
+ x: deltaX,
+ y: deltaY,
+ scale: 0.3,
+ opacity: 0.6,
+ },
+ TIMINGS.sampleToFlame,
+ "easeOutCubic",
+ onComplete,
+ );
+ }
+ }
+
+ // ============================================================================
+ // Main Visualization Class
+ // ============================================================================
+
+ class SamplingVisualization {
+ constructor(container) {
+ this.container = container;
+
+ this.trace = new ExecutionTrace(DEMO_SIMPLE.source, DEMO_SIMPLE.trace);
+
+ this.currentTime = 0;
+ this.isPlaying = false;
+ this.playbackSpeed = TIMINGS.defaultSpeed;
+ this.eventIndex = 0;
+
+ this.sampleInterval = TIMINGS.sampleIntervalDefault;
+ this.lastSampleTime = 0;
+
+ this._createLayout();
+
+ this.effectsManager = new VisualEffectsManager(this.vizColumn);
+
+ this.lastTime = performance.now();
+ this._animate();
+ }
+
+ _createLayout() {
+ this.codePanel = new CodePanel(this.trace.source);
+ this.container.appendChild(this.codePanel.element);
+
+ this.vizColumn = document.createElement("div");
+ this.vizColumn.className = "viz-column";
+ this.container.appendChild(this.vizColumn);
+
+ const stackSection = document.createElement("div");
+ stackSection.className = "stack-section";
+
+ const stackTitle = document.createElement("div");
+ stackTitle.className = "stack-section-title";
+ stackTitle.textContent = "Call Stack";
+ stackSection.appendChild(stackTitle);
+
+ this.stackViz = new DOMStackVisualization();
+ stackSection.appendChild(this.stackViz.element);
+ this.vizColumn.appendChild(stackSection);
+
+ this.samplingPanel = new DOMSamplingPanel();
+ this.samplingPanel.setGroundTruth(this._getGroundTruthFunctions());
+ this.vizColumn.appendChild(this.samplingPanel.element);
+
+ this.controls = new ControlPanel(
+ this.vizColumn,
+ () => this.play(),
+ () => this.pause(),
+ () => this.reset(),
+ (speed) => this.setSpeed(speed),
+ (progress) => this.seek(progress),
+ () => this.step(),
+ (interval) => this.setSampleInterval(interval),
+ );
+ this.controls.setDuration(this.trace.duration);
+ }
+
+ _getGroundTruthFunctions() {
+ const functions = new Set();
+ this.trace.events.forEach((event) => {
+ if (event.type === "call") {
+ functions.add(event.functionName);
+ }
+ });
+ return [...functions];
+ }
+
+ play() {
+ this.isPlaying = true;
+ }
+
+ pause() {
+ this.isPlaying = false;
+ }
+
+ reset() {
+ this.currentTime = 0;
+ this.eventIndex = 0;
+ this.isPlaying = false;
+ this.lastSampleTime = 0;
+ this.stackViz.clear();
+ this.codePanel.reset();
+ this.samplingPanel.reset();
+ this.controls.updateTimeDisplay(0, this.trace.duration);
+ }
+
+ setSpeed(speed) {
+ this.playbackSpeed = speed;
+ }
+
+ setSampleInterval(interval) {
+ this.sampleInterval = interval;
+ this.samplingPanel.setSampleInterval(interval);
+ }
+
+ seek(progress) {
+ this.currentTime = progress * this.trace.duration;
+ this.eventIndex = 0;
+ this.lastSampleTime = 0;
+ this._rebuildState();
+ }
+
+ step() {
+ this.pause();
+
+ const nextEvent = this.trace.getNextEvent(this.currentTime);
+
+ if (nextEvent) {
+ // Calculate delta to reach next event + epsilon
+ const targetTime = nextEvent.timestamp + 0.1;
+ const delta = targetTime - this.currentTime;
+ if (delta > 0) {
+ this._advanceTime(delta);
+ }
+ }
+ }
+
+ _animate(currentTime = performance.now()) {
+ const deltaTime = currentTime - this.lastTime;
+ this.lastTime = currentTime;
+
+ this.update(deltaTime);
+ requestAnimationFrame((t) => this._animate(t));
+ }
+
+ update(deltaTime) {
+ if (!this.isPlaying) {
+ this.controls.updateTimeDisplay(this.currentTime, this.trace.duration);
+ return;
+ }
+
+ const virtualDelta = deltaTime * this.playbackSpeed;
+ this._advanceTime(virtualDelta);
+ }
+
+ _advanceTime(virtualDelta) {
+ this.currentTime += virtualDelta;
+
+ if (this.currentTime >= this.trace.duration) {
+ this.currentTime = this.trace.duration;
+ this.isPlaying = false;
+ this.controls.pause();
+ }
+
+ while (this.eventIndex < this.trace.events.length) {
+ const event = this.trace.events[this.eventIndex];
+
+ if (event.timestamp > this.currentTime) break;
+
+ this._processEvent(event);
+ this.eventIndex++;
+ }
+
+ this.controls.updateTimeDisplay(this.currentTime, this.trace.duration);
+
+ if (this.currentTime - this.lastSampleTime >= this.sampleInterval) {
+ this._takeSample();
+ this.lastSampleTime = this.currentTime;
+ }
+ }
+
+ _processEvent(event) {
+ this.stackViz.processEvent(event);
+
+ if (event.type === "call") {
+ this.codePanel.highlightLine(event.lineno);
+ } else if (event.type === "return") {
+ const currentStack = this.trace.getStackAt(this.currentTime);
+ if (currentStack.length > 0) {
+ this.codePanel.highlightLine(
+ currentStack[currentStack.length - 1].line,
+ );
+ } else {
+ this.codePanel.highlightLine(null);
+ }
+ } else if (event.type === "line") {
+ this.codePanel.highlightLine(event.lineno);
+ }
+ }
+
+ _takeSample() {
+ this.effectsManager.triggerSamplingEffect(
+ this.stackViz,
+ this.samplingPanel,
+ this.currentTime,
+ this.trace,
+ );
+ }
+
+ _rebuildState() {
+ this.stackViz.clear();
+ this.codePanel.reset();
+ this.samplingPanel.reset();
+
+ for (let t = 0; t < this.currentTime; t += this.sampleInterval) {
+ const stack = this.trace.getStackAt(t);
+ this.samplingPanel.addSample(stack);
+ this.lastSampleTime = t;
+ }
+
+ const stack = this.trace.getStackAt(this.currentTime);
+ this.stackViz.updateToMatch(stack);
+
+ if (stack.length > 0) {
+ this.codePanel.highlightLine(stack[stack.length - 1].line);
+ }
+
+ this.eventIndex = this.trace.getEventsUntil(this.currentTime).length;
+ }
+ }
+
+ // ============================================================================
+ // Initialize
+ // ============================================================================
+
+ function init() {
+ // If trace data hasn't been injected yet (local dev), don't initialize
+ if (!DEMO_SIMPLE) return;
+
+ const appContainer = document.getElementById("sampling-profiler-viz");
+ if (appContainer) {
+ new SamplingVisualization(appContainer);
+ }
+ }
+
+ if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", init);
+ } else {
+ init();
+ }
+})();
diff --git a/Doc/bugs.rst b/Doc/bugs.rst
index 0683eebbaf677b..254a22f2622bd8 100644
--- a/Doc/bugs.rst
+++ b/Doc/bugs.rst
@@ -9,7 +9,7 @@ stability. In order to maintain this reputation, the developers would like to
know of any deficiencies you find in Python.
It can be sometimes faster to fix bugs yourself and contribute patches to
-Python as it streamlines the process and involves less people. Learn how to
+Python as it streamlines the process and involves fewer people. Learn how to
:ref:`contribute `.
Documentation bugs
diff --git a/Doc/c-api/arg.rst b/Doc/c-api/arg.rst
index fd6be6a9b67a03..58456a36b96c15 100644
--- a/Doc/c-api/arg.rst
+++ b/Doc/c-api/arg.rst
@@ -516,6 +516,28 @@ API Functions
}
+.. c:function:: int PyArg_ParseArray(PyObject *const *args, Py_ssize_t nargs, const char *format, ...)
+
+ Parse the parameters of a function that takes only array parameters into
+ local variables (that is, a function using the :c:macro:`METH_FASTCALL`
+ calling convention).
+ Returns true on success; on failure, it returns false and raises the
+ appropriate exception.
+
+ .. versionadded:: 3.15
+
+
+.. c:function:: int PyArg_ParseArrayAndKeywords(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames, const char *format, const char * const *kwlist, ...)
+
+ Parse the parameters of a function that takes both array and keyword
+ parameters into local variables (that is, a function using the
+ :c:macro:`METH_FASTCALL` ``|`` :c:macro:`METH_KEYWORDS` calling convention).
+ Returns true on success; on failure, it returns false and raises the
+ appropriate exception.
+
+ .. versionadded:: 3.15
+
+
.. c:function:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
A simpler form of parameter retrieval which does not use a format string to
diff --git a/Doc/c-api/buffer.rst b/Doc/c-api/buffer.rst
index 6bb72a2312be3b..e00b28ca4d7a7e 100644
--- a/Doc/c-api/buffer.rst
+++ b/Doc/c-api/buffer.rst
@@ -10,11 +10,6 @@
Buffer Protocol
---------------
-.. sectionauthor:: Greg Stein
-.. sectionauthor:: Benjamin Peterson
-.. sectionauthor:: Stefan Krah
-
-
Certain objects available in Python wrap access to an underlying memory
array or *buffer*. Such objects include the built-in :class:`bytes` and
:class:`bytearray`, and some extension types like :class:`array.array`.
diff --git a/Doc/c-api/bytes.rst b/Doc/c-api/bytes.rst
index 82c2557368371f..b3cd26a8504715 100644
--- a/Doc/c-api/bytes.rst
+++ b/Doc/c-api/bytes.rst
@@ -371,6 +371,8 @@ Getters
Get the writer size.
+ The function cannot fail.
+
.. c:function:: void* PyBytesWriter_GetData(PyBytesWriter *writer)
Get the writer data: start of the internal buffer.
@@ -378,6 +380,8 @@ Getters
The pointer is valid until :c:func:`PyBytesWriter_Finish` or
:c:func:`PyBytesWriter_Discard` is called on *writer*.
+ The function cannot fail.
+
Low-level API
^^^^^^^^^^^^^
diff --git a/Doc/c-api/code.rst b/Doc/c-api/code.rst
index 048bc2c2154e77..be2c85ec97489e 100644
--- a/Doc/c-api/code.rst
+++ b/Doc/c-api/code.rst
@@ -7,8 +7,6 @@
Code Objects
------------
-.. sectionauthor:: Jeffrey Yasskin
-
Code objects are a low-level detail of the CPython implementation.
Each one represents a chunk of executable code that hasn't yet been
bound into a function.
diff --git a/Doc/c-api/datetime.rst b/Doc/c-api/datetime.rst
index 127d7c9c91a3d5..d7b4e116c49e35 100644
--- a/Doc/c-api/datetime.rst
+++ b/Doc/c-api/datetime.rst
@@ -30,6 +30,10 @@ macros.
This is not compatible with subinterpreters.
+ .. versionchanged:: 3.15
+
+ This macro is now thread safe.
+
.. c:type:: PyDateTime_CAPI
Structure containing the fields for the datetime C API.
@@ -44,6 +48,11 @@ macros.
This variable is only available once :c:macro:`PyDateTime_IMPORT` succeeds.
+ .. versionchanged:: 3.15
+
+ This variable should not be accessed directly as direct access is not thread-safe.
+ Use :c:func:`PyDateTime_IMPORT` instead.
+
.. c:type:: PyDateTime_Date
This subtype of :c:type:`PyObject` represents a Python date object.
diff --git a/Doc/c-api/dict.rst b/Doc/c-api/dict.rst
index 9c4428ced41b5a..f44c18e80758bb 100644
--- a/Doc/c-api/dict.rst
+++ b/Doc/c-api/dict.rst
@@ -2,7 +2,7 @@
.. _dictobjects:
-Dictionary Objects
+Dictionary objects
------------------
.. index:: pair: object; dictionary
@@ -42,6 +42,12 @@ Dictionary Objects
enforces read-only behavior. This is normally used to create a view to
prevent modification of the dictionary for non-dynamic class types.
+ The first argument can be a :class:`dict`, a :class:`frozendict`, or a
+ mapping.
+
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:var:: PyTypeObject PyDictProxy_Type
@@ -58,6 +64,9 @@ Dictionary Objects
Empty an existing dictionary of all key-value pairs.
+ Do nothing if the argument is not a :class:`dict` or a :class:`!dict`
+ subclass.
+
.. c:function:: int PyDict_Contains(PyObject *p, PyObject *key)
@@ -65,6 +74,11 @@ Dictionary Objects
*key*, return ``1``, otherwise return ``0``. On error, return ``-1``.
This is equivalent to the Python expression ``key in p``.
+ The first argument can be a :class:`dict` or a :class:`frozendict`.
+
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: int PyDict_ContainsString(PyObject *p, const char *key)
@@ -72,14 +86,18 @@ Dictionary Objects
:c:expr:`const char*` UTF-8 encoded bytes string, rather than a
:c:expr:`PyObject*`.
+ The first argument can be a :class:`dict` or a :class:`frozendict`.
+
.. versionadded:: 3.13
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: PyObject* PyDict_Copy(PyObject *p)
Return a new dictionary that contains the same key-value pairs as *p*.
-
.. c:function:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
Insert *val* into the dictionary *p* with a key of *key*. *key* must be
@@ -120,8 +138,13 @@ Dictionary Objects
* If the key is missing, set *\*result* to ``NULL`` and return ``0``.
* On error, raise an exception and return ``-1``.
+ The first argument can be a :class:`dict` or a :class:`frozendict`.
+
.. versionadded:: 3.13
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
See also the :c:func:`PyObject_GetItem` function.
@@ -131,6 +154,8 @@ Dictionary Objects
has a key *key*. Return ``NULL`` if the key *key* is missing *without*
setting an exception.
+ The first argument can be a :class:`dict` or a :class:`frozendict`.
+
.. note::
Exceptions that occur while this calls :meth:`~object.__hash__` and
@@ -141,6 +166,9 @@ Dictionary Objects
Calling this API without an :term:`attached thread state` had been allowed for historical
reason. It is no longer allowed.
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: PyObject* PyDict_GetItemWithError(PyObject *p, PyObject *key)
@@ -149,6 +177,9 @@ Dictionary Objects
occurred. Return ``NULL`` **without** an exception set if the key
wasn't present.
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: PyObject* PyDict_GetItemString(PyObject *p, const char *key)
@@ -164,6 +195,9 @@ Dictionary Objects
Prefer using the :c:func:`PyDict_GetItemWithError` function with your own
:c:func:`PyUnicode_FromString` *key* instead.
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: int PyDict_GetItemStringRef(PyObject *p, const char *key, PyObject **result)
@@ -173,6 +207,9 @@ Dictionary Objects
.. versionadded:: 3.13
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: PyObject* PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)
@@ -236,17 +273,32 @@ Dictionary Objects
Return a :c:type:`PyListObject` containing all the items from the dictionary.
+ The first argument can be a :class:`dict` or a :class:`frozendict`.
+
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: PyObject* PyDict_Keys(PyObject *p)
Return a :c:type:`PyListObject` containing all the keys from the dictionary.
+ The first argument can be a :class:`dict` or a :class:`frozendict`.
+
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: PyObject* PyDict_Values(PyObject *p)
Return a :c:type:`PyListObject` containing all the values from the dictionary
*p*.
+ The first argument can be a :class:`dict` or a :class:`frozendict`.
+
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: Py_ssize_t PyDict_Size(PyObject *p)
@@ -255,11 +307,19 @@ Dictionary Objects
Return the number of items in the dictionary. This is equivalent to
``len(p)`` on a dictionary.
+ The argument can be a :class:`dict` or a :class:`frozendict`.
+
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: Py_ssize_t PyDict_GET_SIZE(PyObject *p)
Similar to :c:func:`PyDict_Size`, but without error checking.
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
@@ -274,6 +334,8 @@ Dictionary Objects
value represents offsets within the internal dictionary structure, and
since the structure is sparse, the offsets are not consecutive.
+ The first argument can be a :class:`dict` or a :class:`frozendict`.
+
For example::
PyObject *key, *value;
@@ -307,7 +369,7 @@ Dictionary Objects
}
The function is not thread-safe in the :term:`free-threaded `
- build without external synchronization. You can use
+ build without external synchronization for a mutable :class:`dict`. You can use
:c:macro:`Py_BEGIN_CRITICAL_SECTION` to lock the dictionary while iterating
over it::
@@ -317,6 +379,8 @@ Dictionary Objects
}
Py_END_CRITICAL_SECTION();
+ The function is thread-safe on a :class:`frozendict`.
+
.. note::
On the free-threaded build, this function can be used safely inside a
@@ -327,6 +391,9 @@ Dictionary Objects
:term:`strong reference ` (for example, using
:c:func:`Py_NewRef`).
+ .. versionchanged:: next
+ Also accept :class:`frozendict`.
+
.. c:function:: int PyDict_Merge(PyObject *a, PyObject *b, int override)
Iterate over mapping object *b* adding key-value pairs to dictionary *a*.
@@ -444,7 +511,7 @@ Dictionary Objects
.. versionadded:: 3.12
-Dictionary View Objects
+Dictionary view objects
^^^^^^^^^^^^^^^^^^^^^^^
.. c:function:: int PyDictViewSet_Check(PyObject *op)
@@ -490,7 +557,58 @@ Dictionary View Objects
always succeeds.
-Ordered Dictionaries
+Frozen dictionary objects
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. versionadded:: 3.15
+
+
+.. c:var:: PyTypeObject PyFrozenDict_Type
+
+ This instance of :c:type:`PyTypeObject` represents the Python frozen
+ dictionary type.
+ This is the same object as :class:`frozendict` in the Python layer.
+
+
+.. c:function:: int PyAnyDict_Check(PyObject *p)
+
+ Return true if *p* is a :class:`dict` object, a :class:`frozendict` object,
+ or an instance of a subtype of the :class:`!dict` or :class:`!frozendict`
+ type.
+ This function always succeeds.
+
+
+.. c:function:: int PyAnyDict_CheckExact(PyObject *p)
+
+ Return true if *p* is a :class:`dict` object or a :class:`frozendict` object,
+ but not an instance of a subtype of the :class:`!dict` or
+ :class:`!frozendict` type.
+ This function always succeeds.
+
+
+.. c:function:: int PyFrozenDict_Check(PyObject *p)
+
+ Return true if *p* is a :class:`frozendict` object or an instance of a
+ subtype of the :class:`!frozendict` type.
+ This function always succeeds.
+
+
+.. c:function:: int PyFrozenDict_CheckExact(PyObject *p)
+
+ Return true if *p* is a :class:`frozendict` object, but not an instance of a
+ subtype of the :class:`!frozendict` type.
+ This function always succeeds.
+
+
+.. c:function:: PyObject* PyFrozenDict_New(PyObject *iterable)
+
+ Return a new :class:`frozendict` from an iterable, or ``NULL`` on failure
+ with an exception set.
+
+ Create an empty dictionary if *iterable* is ``NULL``.
+
+
+Ordered dictionaries
^^^^^^^^^^^^^^^^^^^^
Python's C API provides interface for :class:`collections.OrderedDict` from C.
diff --git a/Doc/c-api/exceptions.rst b/Doc/c-api/exceptions.rst
index 59af470f59ff34..8ecd7c62517104 100644
--- a/Doc/c-api/exceptions.rst
+++ b/Doc/c-api/exceptions.rst
@@ -673,28 +673,51 @@ Signal Handling
single: SIGINT (C macro)
single: KeyboardInterrupt (built-in exception)
- This function interacts with Python's signal handling.
+ Handle external interruptions, such as signals or activating a debugger,
+ whose processing has been delayed until it is safe
+ to run Python code and/or raise exceptions.
- If the function is called from the main thread and under the main Python
- interpreter, it checks whether a signal has been sent to the processes
- and if so, invokes the corresponding signal handler. If the :mod:`signal`
- module is supported, this can invoke a signal handler written in Python.
+ For example, pressing :kbd:`Ctrl-C` causes a terminal to send the
+ :py:data:`signal.SIGINT` signal.
+ This function executes the corresponding Python signal handler, which,
+ by default, raises the :exc:`KeyboardInterrupt` exception.
- The function attempts to handle all pending signals, and then returns ``0``.
- However, if a Python signal handler raises an exception, the error
- indicator is set and the function returns ``-1`` immediately (such that
- other pending signals may not have been handled yet: they will be on the
- next :c:func:`PyErr_CheckSignals()` invocation).
+ :c:func:`!PyErr_CheckSignals` should be called by long-running C code
+ frequently enough so that the response appears immediate to humans.
- If the function is called from a non-main thread, or under a non-main
- Python interpreter, it does nothing and returns ``0``.
+ Handlers invoked by this function currently include:
- This function can be called by long-running C code that wants to
- be interruptible by user requests (such as by pressing Ctrl-C).
+ - Signal handlers, including Python functions registered using
+ the :mod:`signal` module.
- .. note::
- The default Python signal handler for :c:macro:`!SIGINT` raises the
- :exc:`KeyboardInterrupt` exception.
+ Signal handlers are only run in the main thread of the main interpreter.
+
+ (This is where the function got the name: originally, signals
+ were the only way to interrupt the interpreter.)
+
+ - Running the garbage collector, if necessary.
+
+ - Executing a pending :ref:`remote debugger ` script.
+
+ - Raise the exception set by :c:func:`PyThreadState_SetAsyncExc`.
+
+ If any handler raises an exception, immediately return ``-1`` with that
+ exception set.
+ Any remaining interruptions are left to be processed on the next
+ :c:func:`PyErr_CheckSignals()` invocation, if appropriate.
+
+ If all handlers finish successfully, or there are no handlers to run,
+ return ``0``.
+
+ .. versionchanged:: 3.12
+ This function may now invoke the garbage collector.
+
+ .. versionchanged:: 3.14
+ This function may now execute a remote debugger script, if remote
+ debugging is enabled.
+
+ .. versionchanged:: 3.15
+ The exception set by :c:func:`PyThreadState_SetAsyncExc` is now raised.
.. c:function:: void PyErr_SetInterrupt()
@@ -1119,6 +1142,8 @@ Exception types
* :exc:`FloatingPointError`
* * .. c:var:: PyObject *PyExc_GeneratorExit
* :exc:`GeneratorExit`
+ * * .. c:var:: PyObject *PyExc_ImportCycleError
+ * :exc:`ImportCycleError`
* * .. c:var:: PyObject *PyExc_ImportError
* :exc:`ImportError`
* * .. c:var:: PyObject *PyExc_IndentationError
diff --git a/Doc/c-api/float.rst b/Doc/c-api/float.rst
index b0d440580b9886..6e83e01344a9b2 100644
--- a/Doc/c-api/float.rst
+++ b/Doc/c-api/float.rst
@@ -80,7 +80,7 @@ Floating-Point Objects
.. c:macro:: Py_INFINITY
- This macro expands a to constant expression of type :c:expr:`double`, that
+ This macro expands to a constant expression of type :c:expr:`double`, that
represents the positive infinity.
It is equivalent to the :c:macro:`!INFINITY` macro from the C11 standard
@@ -92,7 +92,7 @@ Floating-Point Objects
.. c:macro:: Py_NAN
- This macro expands a to constant expression of type :c:expr:`double`, that
+ This macro expands to a constant expression of type :c:expr:`double`, that
represents a quiet not-a-number (qNaN) value.
On most platforms, this is equivalent to the :c:macro:`!NAN` macro from
@@ -201,8 +201,8 @@ NaNs (if such things exist on the platform) isn't handled correctly, and
attempting to unpack a bytes string containing an IEEE INF or NaN will raise an
exception.
-Note that NaNs type may not be preserved on IEEE platforms (signaling NaN become
-quiet NaN), for example on x86 systems in 32-bit mode.
+Note that NaN type may not be preserved on IEEE platforms (signaling NaNs become
+quiet NaNs), for example on x86 systems in 32-bit mode.
On non-IEEE platforms with more precision, or larger dynamic range, than IEEE
754 supports, not all values can be packed; on non-IEEE platforms with less
@@ -216,7 +216,7 @@ Pack functions
The pack routines write 2, 4 or 8 bytes, starting at *p*. *le* is an
:c:expr:`int` argument, non-zero if you want the bytes string in little-endian
-format (exponent last, at ``p+1``, ``p+3``, or ``p+6`` ``p+7``), zero if you
+format (exponent last, at ``p+1``, ``p+3``, or ``p+6`` and ``p+7``), zero if you
want big-endian format (exponent first, at *p*). The :c:macro:`PY_BIG_ENDIAN`
constant can be used to use the native endian: it is equal to ``1`` on big
endian processor, or ``0`` on little endian processor.
@@ -224,11 +224,6 @@ endian processor, or ``0`` on little endian processor.
Return value: ``0`` if all is OK, ``-1`` if error (and an exception is set,
most likely :exc:`OverflowError`).
-There are two problems on non-IEEE platforms:
-
-* What this does is undefined if *x* is a NaN or infinity.
-* ``-0.0`` and ``+0.0`` produce the same bytes string.
-
.. c:function:: int PyFloat_Pack2(double x, char *p, int le)
Pack a C double as the IEEE 754 binary16 half-precision format.
@@ -256,9 +251,6 @@ Return value: The unpacked double. On error, this is ``-1.0`` and
:c:func:`PyErr_Occurred` is true (and an exception is set, most likely
:exc:`OverflowError`).
-Note that on a non-IEEE platform this will refuse to unpack a bytes string that
-represents a NaN or infinity.
-
.. c:function:: double PyFloat_Unpack2(const char *p, int le)
Unpack the IEEE 754 binary16 half-precision format as a C double.
diff --git a/Doc/c-api/frame.rst b/Doc/c-api/frame.rst
index fb17cf7f1da6b2..967cfc727655ec 100644
--- a/Doc/c-api/frame.rst
+++ b/Doc/c-api/frame.rst
@@ -50,6 +50,7 @@ See also :ref:`Reflection `.
Return a :term:`strong reference`, or ``NULL`` if *frame* has no outer
frame.
+ This raises no exceptions.
.. versionadded:: 3.9
diff --git a/Doc/c-api/import.rst b/Doc/c-api/import.rst
index a28c0713dd3b2f..367490732b994f 100644
--- a/Doc/c-api/import.rst
+++ b/Doc/c-api/import.rst
@@ -346,6 +346,58 @@ Importing Modules
.. versionadded:: 3.14
+.. c:function:: PyImport_LazyImportsMode PyImport_GetLazyImportsMode()
+
+ Gets the current lazy imports mode.
+
+ .. versionadded:: 3.15
+
+.. c:function:: PyObject* PyImport_GetLazyImportsFilter()
+
+ Return a :term:`strong reference` to the current lazy imports filter,
+ or ``NULL`` if none exists. This function always succeeds.
+
+ .. versionadded:: 3.15
+
+.. c:function:: int PyImport_SetLazyImportsMode(PyImport_LazyImportsMode mode)
+
+ Similar to :c:func:`PyImport_ImportModuleAttr`, but names are UTF-8 encoded
+ strings instead of Python :class:`str` objects.
+
+ This function always returns ``0``.
+
+ .. versionadded:: 3.15
+
+.. c:function:: int PyImport_SetLazyImportsFilter(PyObject *filter)
+
+ Sets the current lazy imports filter. The *filter* should be a callable that
+ will receive ``(importing_module_name, imported_module_name, [fromlist])``
+ when an import can potentially be lazy and that must return ``True`` if
+ the import should be lazy and ``False`` otherwise.
+
+ Return ``0`` on success and ``-1`` with an exception set otherwise.
+
+ .. versionadded:: 3.15
+
+.. c:type:: PyImport_LazyImportsMode
+
+ Enumeration of possible lazy import modes.
+
+ .. c:enumerator:: PyImport_LAZY_NORMAL
+
+ Respect the ``lazy`` keyword in source code. This is the default mode.
+
+ .. c:enumerator:: PyImport_LAZY_ALL
+
+ Make all imports lazy by default.
+
+ .. c:enumerator:: PyImport_LAZY_NONE
+
+ Disable lazy imports entirely. Even explicit ``lazy`` statements become
+ eager imports.
+
+ .. versionadded:: 3.15
+
.. c:function:: PyObject* PyImport_CreateModuleFromInitfunc(PyObject *spec, PyObject* (*initfunc)(void))
This function is a building block that enables embedders to implement
diff --git a/Doc/c-api/index.rst b/Doc/c-api/index.rst
index e9df2a304d975b..eabe00f4004001 100644
--- a/Doc/c-api/index.rst
+++ b/Doc/c-api/index.rst
@@ -1,7 +1,7 @@
.. _c-api-index:
##################################
- Python/C API Reference Manual
+ Python/C API reference manual
##################################
This manual documents the API used by C and C++ programmers who want to write
@@ -21,7 +21,12 @@ document the API functions in detail.
utilities.rst
abstract.rst
concrete.rst
- init.rst
+ interp-lifecycle.rst
+ threads.rst
+ synchronization.rst
+ tls.rst
+ subinterpreters.rst
+ profiling.rst
init_config.rst
memory.rst
objimpl.rst
diff --git a/Doc/c-api/init.rst b/Doc/c-api/init.rst
index 7411644f9e110b..e56c67f95348c7 100644
--- a/Doc/c-api/init.rst
+++ b/Doc/c-api/init.rst
@@ -1,2759 +1,13 @@
-.. highlight:: c
+:orphan:
+Initialization, finalization, and threads
+=========================================
-.. _initialization:
+This page has been split up into the following:
-*****************************************
-Initialization, Finalization, and Threads
-*****************************************
-
-See :ref:`Python Initialization Configuration ` for details
-on how to configure the interpreter prior to initialization.
-
-.. _pre-init-safe:
-
-Before Python Initialization
-============================
-
-In an application embedding Python, the :c:func:`Py_Initialize` function must
-be called before using any other Python/C API functions; with the exception of
-a few functions and the :ref:`global configuration variables
-`.
-
-The following functions can be safely called before Python is initialized:
-
-* Functions that initialize the interpreter:
-
- * :c:func:`Py_Initialize`
- * :c:func:`Py_InitializeEx`
- * :c:func:`Py_InitializeFromConfig`
- * :c:func:`Py_BytesMain`
- * :c:func:`Py_Main`
- * the runtime pre-initialization functions covered in :ref:`init-config`
-
-* Configuration functions:
-
- * :c:func:`PyImport_AppendInittab`
- * :c:func:`PyImport_ExtendInittab`
- * :c:func:`!PyInitFrozenExtensions`
- * :c:func:`PyMem_SetAllocator`
- * :c:func:`PyMem_SetupDebugHooks`
- * :c:func:`PyObject_SetArenaAllocator`
- * :c:func:`Py_SetProgramName`
- * :c:func:`Py_SetPythonHome`
- * the configuration functions covered in :ref:`init-config`
-
-* Informative functions:
-
- * :c:func:`Py_IsInitialized`
- * :c:func:`PyMem_GetAllocator`
- * :c:func:`PyObject_GetArenaAllocator`
- * :c:func:`Py_GetBuildInfo`
- * :c:func:`Py_GetCompiler`
- * :c:func:`Py_GetCopyright`
- * :c:func:`Py_GetPlatform`
- * :c:func:`Py_GetVersion`
- * :c:func:`Py_IsInitialized`
-
-* Utilities:
-
- * :c:func:`Py_DecodeLocale`
- * the status reporting and utility functions covered in :ref:`init-config`
-
-* Memory allocators:
-
- * :c:func:`PyMem_RawMalloc`
- * :c:func:`PyMem_RawRealloc`
- * :c:func:`PyMem_RawCalloc`
- * :c:func:`PyMem_RawFree`
-
-* Synchronization:
-
- * :c:func:`PyMutex_Lock`
- * :c:func:`PyMutex_Unlock`
-
-.. note::
-
- Despite their apparent similarity to some of the functions listed above,
- the following functions **should not be called** before the interpreter has
- been initialized: :c:func:`Py_EncodeLocale`, :c:func:`PyEval_InitThreads`, and
- :c:func:`Py_RunMain`.
-
-
-.. _global-conf-vars:
-
-Global configuration variables
-==============================
-
-Python has variables for the global configuration to control different features
-and options. By default, these flags are controlled by :ref:`command line
-options `.
-
-When a flag is set by an option, the value of the flag is the number of times
-that the option was set. For example, ``-b`` sets :c:data:`Py_BytesWarningFlag`
-to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2.
-
-.. c:var:: int Py_BytesWarningFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.bytes_warning` should be used instead, see :ref:`Python
- Initialization Configuration `.
-
- Issue a warning when comparing :class:`bytes` or :class:`bytearray` with
- :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater
- or equal to ``2``.
-
- Set by the :option:`-b` option.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_DebugFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.parser_debug` should be used instead, see :ref:`Python
- Initialization Configuration `.
-
- Turn on parser debugging output (for expert only, depending on compilation
- options).
-
- Set by the :option:`-d` option and the :envvar:`PYTHONDEBUG` environment
- variable.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_DontWriteBytecodeFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.write_bytecode` should be used instead, see :ref:`Python
- Initialization Configuration `.
-
- If set to non-zero, Python won't try to write ``.pyc`` files on the
- import of source modules.
-
- Set by the :option:`-B` option and the :envvar:`PYTHONDONTWRITEBYTECODE`
- environment variable.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_FrozenFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.pathconfig_warnings` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- Private flag used by ``_freeze_module`` and ``frozenmain`` programs.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_HashRandomizationFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.hash_seed` and :c:member:`PyConfig.use_hash_seed` should
- be used instead, see :ref:`Python Initialization Configuration
- `.
-
- Set to ``1`` if the :envvar:`PYTHONHASHSEED` environment variable is set to
- a non-empty string.
-
- If the flag is non-zero, read the :envvar:`PYTHONHASHSEED` environment
- variable to initialize the secret hash seed.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_IgnoreEnvironmentFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.use_environment` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- Ignore all :envvar:`!PYTHON*` environment variables, e.g.
- :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
-
- Set by the :option:`-E` and :option:`-I` options.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_InspectFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.inspect` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- When a script is passed as first argument or the :option:`-c` option is used,
- enter interactive mode after executing the script or the command, even when
- :data:`sys.stdin` does not appear to be a terminal.
-
- Set by the :option:`-i` option and the :envvar:`PYTHONINSPECT` environment
- variable.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_InteractiveFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.interactive` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- Set by the :option:`-i` option.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_IsolatedFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.isolated` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- Run Python in isolated mode. In isolated mode :data:`sys.path` contains
- neither the script's directory nor the user's site-packages directory.
-
- Set by the :option:`-I` option.
-
- .. versionadded:: 3.4
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_LegacyWindowsFSEncodingFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyPreConfig.legacy_windows_fs_encoding` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- If the flag is non-zero, use the ``mbcs`` encoding with ``replace`` error
- handler, instead of the UTF-8 encoding with ``surrogatepass`` error handler,
- for the :term:`filesystem encoding and error handler`.
-
- Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment
- variable is set to a non-empty string.
-
- See :pep:`529` for more details.
-
- .. availability:: Windows.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_LegacyWindowsStdioFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.legacy_windows_stdio` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- If the flag is non-zero, use :class:`io.FileIO` instead of
- :class:`!io._WindowsConsoleIO` for :mod:`sys` standard streams.
-
- Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment
- variable is set to a non-empty string.
-
- See :pep:`528` for more details.
-
- .. availability:: Windows.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_NoSiteFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.site_import` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- Disable the import of the module :mod:`site` and the site-dependent
- manipulations of :data:`sys.path` that it entails. Also disable these
- manipulations if :mod:`site` is explicitly imported later (call
- :func:`site.main` if you want them to be triggered).
-
- Set by the :option:`-S` option.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_NoUserSiteDirectory
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.user_site_directory` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- Don't add the :data:`user site-packages directory ` to
- :data:`sys.path`.
-
- Set by the :option:`-s` and :option:`-I` options, and the
- :envvar:`PYTHONNOUSERSITE` environment variable.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_OptimizeFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.optimization_level` should be used instead, see
- :ref:`Python Initialization Configuration `.
-
- Set by the :option:`-O` option and the :envvar:`PYTHONOPTIMIZE` environment
- variable.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_QuietFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.quiet` should be used instead, see :ref:`Python
- Initialization Configuration `.
-
- Don't display the copyright and version messages even in interactive mode.
-
- Set by the :option:`-q` option.
-
- .. versionadded:: 3.2
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_UnbufferedStdioFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.buffered_stdio` should be used instead, see :ref:`Python
- Initialization Configuration `.
-
- Force the stdout and stderr streams to be unbuffered.
-
- Set by the :option:`-u` option and the :envvar:`PYTHONUNBUFFERED`
- environment variable.
-
- .. deprecated-removed:: 3.12 3.15
-
-.. c:var:: int Py_VerboseFlag
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.verbose` should be used instead, see :ref:`Python
- Initialization Configuration `.
-
- Print a message each time a module is initialized, showing the place
- (filename or built-in module) from which it is loaded. If greater or equal
- to ``2``, print a message for each file that is checked for when
- searching for a module. Also provides information on module cleanup at exit.
-
- Set by the :option:`-v` option and the :envvar:`PYTHONVERBOSE` environment
- variable.
-
- .. deprecated-removed:: 3.12 3.15
-
-
-Initializing and finalizing the interpreter
-===========================================
-
-
-.. c:function:: void Py_Initialize()
-
- .. index::
- single: PyEval_InitThreads()
- single: modules (in module sys)
- single: path (in module sys)
- pair: module; builtins
- pair: module; __main__
- pair: module; sys
- triple: module; search; path
- single: Py_FinalizeEx (C function)
-
- Initialize the Python interpreter. In an application embedding Python,
- this should be called before using any other Python/C API functions; see
- :ref:`Before Python Initialization ` for the few exceptions.
-
- This initializes the table of loaded modules (``sys.modules``), and creates
- the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`.
- It also initializes the module search path (``sys.path``). It does not set
- ``sys.argv``; use the :ref:`Python Initialization Configuration `
- API for that. This is a no-op when called for a second time (without calling
- :c:func:`Py_FinalizeEx` first). There is no return value; it is a fatal
- error if the initialization fails.
-
- Use :c:func:`Py_InitializeFromConfig` to customize the
- :ref:`Python Initialization Configuration `.
-
- .. note::
- On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``,
- which will also affect non-Python uses of the console using the C Runtime.
-
-
-.. c:function:: void Py_InitializeEx(int initsigs)
-
- This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If
- *initsigs* is ``0``, it skips initialization registration of signal handlers,
- which may be useful when CPython is embedded as part of a larger application.
-
- Use :c:func:`Py_InitializeFromConfig` to customize the
- :ref:`Python Initialization Configuration `.
-
-
-.. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config)
-
- Initialize Python from *config* configuration, as described in
- :ref:`init-from-config`.
-
- See the :ref:`init-config` section for details on pre-initializing the
- interpreter, populating the runtime configuration structure, and querying
- the returned status structure.
-
-
-.. c:function:: int Py_IsInitialized()
-
- Return true (nonzero) when the Python interpreter has been initialized, false
- (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until
- :c:func:`Py_Initialize` is called again.
-
-
-.. c:function:: int Py_IsFinalizing()
-
- Return true (non-zero) if the main Python interpreter is
- :term:`shutting down `. Return false (zero) otherwise.
-
- .. versionadded:: 3.13
-
-
-.. c:function:: int Py_FinalizeEx()
-
- Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of
- Python/C API functions, and destroy all sub-interpreters (see
- :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since
- the last call to :c:func:`Py_Initialize`. This is a no-op when called for a second
- time (without calling :c:func:`Py_Initialize` again first).
-
- Since this is the reverse of :c:func:`Py_Initialize`, it should be called
- in the same thread with the same interpreter active. That means
- the main thread and the main interpreter.
- This should never be called while :c:func:`Py_RunMain` is running.
-
- Normally the return value is ``0``.
- If there were errors during finalization (flushing buffered data),
- ``-1`` is returned.
-
- Note that Python will do a best effort at freeing all memory allocated by the Python
- interpreter. Therefore, any C-Extension should make sure to correctly clean up all
- of the preveiously allocated PyObjects before using them in subsequent calls to
- :c:func:`Py_Initialize`. Otherwise it could introduce vulnerabilities and incorrect
- behavior.
-
- This function is provided for a number of reasons. An embedding application
- might want to restart Python without having to restart the application itself.
- An application that has loaded the Python interpreter from a dynamically
- loadable library (or DLL) might want to free all memory allocated by Python
- before unloading the DLL. During a hunt for memory leaks in an application a
- developer might want to free all memory allocated by Python before exiting from
- the application.
-
- **Bugs and caveats:** The destruction of modules and objects in modules is done
- in random order; this may cause destructors (:meth:`~object.__del__` methods) to fail
- when they depend on other objects (even functions) or modules. Dynamically
- loaded extension modules loaded by Python are not unloaded. Small amounts of
- memory allocated by the Python interpreter may not be freed (if you find a leak,
- please report it). Memory tied up in circular references between objects is not
- freed. Interned strings will all be deallocated regardless of their reference count.
- Some memory allocated by extension modules may not be freed. Some extensions may not
- work properly if their initialization routine is called more than once; this can
- happen if an application calls :c:func:`Py_Initialize` and :c:func:`Py_FinalizeEx`
- more than once. :c:func:`Py_FinalizeEx` must not be called recursively from
- within itself. Therefore, it must not be called by any code that may be run
- as part of the interpreter shutdown process, such as :py:mod:`atexit`
- handlers, object finalizers, or any code that may be run while flushing the
- stdout and stderr files.
-
- .. audit-event:: cpython._PySys_ClearAuditHooks "" c.Py_FinalizeEx
-
- .. versionadded:: 3.6
-
-
-.. c:function:: void Py_Finalize()
-
- This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that
- disregards the return value.
-
-
-.. c:function:: int Py_BytesMain(int argc, char **argv)
-
- Similar to :c:func:`Py_Main` but *argv* is an array of bytes strings,
- allowing the calling application to delegate the text decoding step to
- the CPython runtime.
-
- .. versionadded:: 3.8
-
-
-.. c:function:: int Py_Main(int argc, wchar_t **argv)
-
- The main program for the standard interpreter, encapsulating a full
- initialization/finalization cycle, as well as additional
- behaviour to implement reading configurations settings from the environment
- and command line, and then executing ``__main__`` in accordance with
- :ref:`using-on-cmdline`.
-
- This is made available for programs which wish to support the full CPython
- command line interface, rather than just embedding a Python runtime in a
- larger application.
-
- The *argc* and *argv* parameters are similar to those which are passed to a
- C program's :c:func:`main` function, except that the *argv* entries are first
- converted to ``wchar_t`` using :c:func:`Py_DecodeLocale`. It is also
- important to note that the argument list entries may be modified to point to
- strings other than those passed in (however, the contents of the strings
- pointed to by the argument list are not modified).
-
- The return value is ``2`` if the argument list does not represent a valid
- Python command line, and otherwise the same as :c:func:`Py_RunMain`.
-
- In terms of the CPython runtime configuration APIs documented in the
- :ref:`runtime configuration ` section (and without accounting
- for error handling), ``Py_Main`` is approximately equivalent to::
-
- PyConfig config;
- PyConfig_InitPythonConfig(&config);
- PyConfig_SetArgv(&config, argc, argv);
- Py_InitializeFromConfig(&config);
- PyConfig_Clear(&config);
-
- Py_RunMain();
-
- In normal usage, an embedding application will call this function
- *instead* of calling :c:func:`Py_Initialize`, :c:func:`Py_InitializeEx` or
- :c:func:`Py_InitializeFromConfig` directly, and all settings will be applied
- as described elsewhere in this documentation. If this function is instead
- called *after* a preceding runtime initialization API call, then exactly
- which environmental and command line configuration settings will be updated
- is version dependent (as it depends on which settings correctly support
- being modified after they have already been set once when the runtime was
- first initialized).
-
-
-.. c:function:: int Py_RunMain(void)
-
- Executes the main module in a fully configured CPython runtime.
-
- Executes the command (:c:member:`PyConfig.run_command`), the script
- (:c:member:`PyConfig.run_filename`) or the module
- (:c:member:`PyConfig.run_module`) specified on the command line or in the
- configuration. If none of these values are set, runs the interactive Python
- prompt (REPL) using the ``__main__`` module's global namespace.
-
- If :c:member:`PyConfig.inspect` is not set (the default), the return value
- will be ``0`` if the interpreter exits normally (that is, without raising
- an exception), the exit status of an unhandled :exc:`SystemExit`, or ``1``
- for any other unhandled exception.
-
- If :c:member:`PyConfig.inspect` is set (such as when the :option:`-i` option
- is used), rather than returning when the interpreter exits, execution will
- instead resume in an interactive Python prompt (REPL) using the ``__main__``
- module's global namespace. If the interpreter exited with an exception, it
- is immediately raised in the REPL session. The function return value is
- then determined by the way the *REPL session* terminates: ``0``, ``1``, or
- the status of a :exc:`SystemExit`, as specified above.
-
- This function always finalizes the Python interpreter before it returns.
-
- See :ref:`Python Configuration ` for an example of a
- customized Python that always runs in isolated mode using
- :c:func:`Py_RunMain`.
-
-.. c:function:: int PyUnstable_AtExit(PyInterpreterState *interp, void (*func)(void *), void *data)
-
- Register an :mod:`atexit` callback for the target interpreter *interp*.
- This is similar to :c:func:`Py_AtExit`, but takes an explicit interpreter and
- data pointer for the callback.
-
- There must be an :term:`attached thread state` for *interp*.
-
- .. versionadded:: 3.13
-
-Process-wide parameters
-=======================
-
-
-.. c:function:: void Py_SetProgramName(const wchar_t *name)
-
- .. index::
- single: Py_Initialize()
- single: main()
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.program_name` should be used instead, see :ref:`Python
- Initialization Configuration `.
-
- This function should be called before :c:func:`Py_Initialize` is called for
- the first time, if it is called at all. It tells the interpreter the value
- of the ``argv[0]`` argument to the :c:func:`main` function of the program
- (converted to wide characters).
- This is used by some other functions below to find
- the Python run-time libraries relative to the interpreter executable. The
- default value is ``'python'``. The argument should point to a
- zero-terminated wide character string in static storage whose contents will not
- change for the duration of the program's execution. No code in the Python
- interpreter will change the contents of this storage.
-
- Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
- :c:expr:`wchar_t*` string.
-
- .. deprecated-removed:: 3.11 3.15
-
-
-.. c:function:: const char* Py_GetVersion()
-
- Return the version of this Python interpreter. This is a string that looks
- something like ::
-
- "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
-
- .. index:: single: version (in module sys)
-
- The first word (up to the first space character) is the current Python version;
- the first characters are the major and minor version separated by a
- period. The returned string points into static storage; the caller should not
- modify its value. The value is available to Python code as :data:`sys.version`.
-
- See also the :c:var:`Py_Version` constant.
-
-
-.. c:function:: const char* Py_GetPlatform()
-
- .. index:: single: platform (in module sys)
-
- Return the platform identifier for the current platform. On Unix, this is
- formed from the "official" name of the operating system, converted to lower
- case, followed by the major revision number; e.g., for Solaris 2.x, which is
- also known as SunOS 5.x, the value is ``'sunos5'``. On macOS, it is
- ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
- static storage; the caller should not modify its value. The value is available
- to Python code as ``sys.platform``.
-
-
-.. c:function:: const char* Py_GetCopyright()
-
- Return the official copyright string for the current Python version, for example
-
- ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
-
- .. index:: single: copyright (in module sys)
-
- The returned string points into static storage; the caller should not modify its
- value. The value is available to Python code as ``sys.copyright``.
-
-
-.. c:function:: const char* Py_GetCompiler()
-
- Return an indication of the compiler used to build the current Python version,
- in square brackets, for example::
-
- "[GCC 2.7.2.2]"
-
- .. index:: single: version (in module sys)
-
- The returned string points into static storage; the caller should not modify its
- value. The value is available to Python code as part of the variable
- ``sys.version``.
-
-
-.. c:function:: const char* Py_GetBuildInfo()
-
- Return information about the sequence number and build date and time of the
- current Python interpreter instance, for example ::
-
- "#67, Aug 1 1997, 22:34:28"
-
- .. index:: single: version (in module sys)
-
- The returned string points into static storage; the caller should not modify its
- value. The value is available to Python code as part of the variable
- ``sys.version``.
-
-
-.. c:function:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
-
- .. index::
- single: main()
- single: Py_FatalError()
- single: argv (in module sys)
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.argv`, :c:member:`PyConfig.parse_argv` and
- :c:member:`PyConfig.safe_path` should be used instead, see :ref:`Python
- Initialization Configuration `.
-
- Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
- similar to those passed to the program's :c:func:`main` function with the
- difference that the first entry should refer to the script file to be
- executed rather than the executable hosting the Python interpreter. If there
- isn't a script that will be run, the first entry in *argv* can be an empty
- string. If this function fails to initialize :data:`sys.argv`, a fatal
- condition is signalled using :c:func:`Py_FatalError`.
-
- If *updatepath* is zero, this is all the function does. If *updatepath*
- is non-zero, the function also modifies :data:`sys.path` according to the
- following algorithm:
-
- - If the name of an existing script is passed in ``argv[0]``, the absolute
- path of the directory where the script is located is prepended to
- :data:`sys.path`.
- - Otherwise (that is, if *argc* is ``0`` or ``argv[0]`` doesn't point
- to an existing file name), an empty string is prepended to
- :data:`sys.path`, which is the same as prepending the current working
- directory (``"."``).
-
- Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
- :c:expr:`wchar_t*` string.
-
- See also :c:member:`PyConfig.orig_argv` and :c:member:`PyConfig.argv`
- members of the :ref:`Python Initialization Configuration `.
-
- .. note::
- It is recommended that applications embedding the Python interpreter
- for purposes other than executing a single script pass ``0`` as *updatepath*,
- and update :data:`sys.path` themselves if desired.
- See :cve:`2008-5983`.
-
- On versions before 3.1.3, you can achieve the same effect by manually
- popping the first :data:`sys.path` element after having called
- :c:func:`PySys_SetArgv`, for example using::
-
- PyRun_SimpleString("import sys; sys.path.pop(0)\n");
-
- .. versionadded:: 3.1.3
-
- .. XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params;
- check w/ Guido.
-
- .. deprecated-removed:: 3.11 3.15
-
-
-.. c:function:: void PySys_SetArgv(int argc, wchar_t **argv)
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.argv` and :c:member:`PyConfig.parse_argv` should be used
- instead, see :ref:`Python Initialization Configuration `.
-
- This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set
- to ``1`` unless the :program:`python` interpreter was started with the
- :option:`-I`.
-
- Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
- :c:expr:`wchar_t*` string.
-
- See also :c:member:`PyConfig.orig_argv` and :c:member:`PyConfig.argv`
- members of the :ref:`Python Initialization Configuration `.
-
- .. versionchanged:: 3.4 The *updatepath* value depends on :option:`-I`.
-
- .. deprecated-removed:: 3.11 3.15
-
-
-.. c:function:: void Py_SetPythonHome(const wchar_t *home)
-
- This API is kept for backward compatibility: setting
- :c:member:`PyConfig.home` should be used instead, see :ref:`Python
- Initialization Configuration `.
-
- Set the default "home" directory, that is, the location of the standard
- Python libraries. See :envvar:`PYTHONHOME` for the meaning of the
- argument string.
-
- The argument should point to a zero-terminated character string in static
- storage whose contents will not change for the duration of the program's
- execution. No code in the Python interpreter will change the contents of
- this storage.
-
- Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
- :c:expr:`wchar_t*` string.
-
- .. deprecated-removed:: 3.11 3.15
-
-
-.. _threads:
-
-Thread State and the Global Interpreter Lock
-============================================
-
-.. index::
- single: global interpreter lock
- single: interpreter lock
- single: lock, interpreter
-
-Unless on a :term:`free-threaded ` build of :term:`CPython`,
-the Python interpreter is not fully thread-safe. In order to support
-multi-threaded Python programs, there's a global lock, called the :term:`global
-interpreter lock` or :term:`GIL`, that must be held by the current thread before
-it can safely access Python objects. Without the lock, even the simplest
-operations could cause problems in a multi-threaded program: for example, when
-two threads simultaneously increment the reference count of the same object, the
-reference count could end up being incremented only once instead of twice.
-
-.. index:: single: setswitchinterval (in module sys)
-
-Therefore, the rule exists that only the thread that has acquired the
-:term:`GIL` may operate on Python objects or call Python/C API functions.
-In order to emulate concurrency of execution, the interpreter regularly
-tries to switch threads (see :func:`sys.setswitchinterval`). The lock is also
-released around potentially blocking I/O operations like reading or writing
-a file, so that other Python threads can run in the meantime.
-
-.. index::
- single: PyThreadState (C type)
-
-The Python interpreter keeps some thread-specific bookkeeping information
-inside a data structure called :c:type:`PyThreadState`, known as a :term:`thread state`.
-Each OS thread has a thread-local pointer to a :c:type:`PyThreadState`; a thread state
-referenced by this pointer is considered to be :term:`attached `.
-
-A thread can only have one :term:`attached thread state` at a time. An attached
-thread state is typically analogous with holding the :term:`GIL`, except on
-:term:`free-threaded ` builds. On builds with the :term:`GIL` enabled,
-:term:`attaching ` a thread state will block until the :term:`GIL`
-can be acquired. However, even on builds with the :term:`GIL` disabled, it is still required
-to have an attached thread state to call most of the C API.
-
-In general, there will always be an :term:`attached thread state` when using Python's C API.
-Only in some specific cases (such as in a :c:macro:`Py_BEGIN_ALLOW_THREADS` block) will the
-thread not have an attached thread state. If uncertain, check if :c:func:`PyThreadState_GetUnchecked` returns
-``NULL``.
-
-Detaching the thread state from extension code
-----------------------------------------------
-
-Most extension code manipulating the :term:`thread state` has the following simple
-structure::
-
- Save the thread state in a local variable.
- ... Do some blocking I/O operation ...
- Restore the thread state from the local variable.
-
-This is so common that a pair of macros exists to simplify it::
-
- Py_BEGIN_ALLOW_THREADS
- ... Do some blocking I/O operation ...
- Py_END_ALLOW_THREADS
-
-.. index::
- single: Py_BEGIN_ALLOW_THREADS (C macro)
- single: Py_END_ALLOW_THREADS (C macro)
-
-The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
-hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the
-block.
-
-The block above expands to the following code::
-
- PyThreadState *_save;
-
- _save = PyEval_SaveThread();
- ... Do some blocking I/O operation ...
- PyEval_RestoreThread(_save);
-
-.. index::
- single: PyEval_RestoreThread (C function)
- single: PyEval_SaveThread (C function)
-
-Here is how these functions work:
-
-The :term:`attached thread state` holds the :term:`GIL` for the entire interpreter. When detaching
-the :term:`attached thread state`, the :term:`GIL` is released, allowing other threads to attach
-a thread state to their own thread, thus getting the :term:`GIL` and can start executing.
-The pointer to the prior :term:`attached thread state` is stored as a local variable.
-Upon reaching :c:macro:`Py_END_ALLOW_THREADS`, the thread state that was
-previously :term:`attached ` is passed to :c:func:`PyEval_RestoreThread`.
-This function will block until another releases its :term:`thread state `,
-thus allowing the old :term:`thread state ` to get re-attached and the
-C API can be called again.
-
-For :term:`free-threaded ` builds, the :term:`GIL` is normally
-out of the question, but detaching the :term:`thread state ` is still required
-for blocking I/O and long operations. The difference is that threads don't have to wait for the :term:`GIL`
-to be released to attach their thread state, allowing true multi-core parallelism.
-
-.. note::
- Calling system I/O functions is the most common use case for detaching
- the :term:`thread state `, but it can also be useful before calling
- long-running computations which don't need access to Python objects, such
- as compression or cryptographic functions operating over memory buffers.
- For example, the standard :mod:`zlib` and :mod:`hashlib` modules detach the
- :term:`thread state ` when compressing or hashing data.
-
-
-.. _gilstate:
-
-Non-Python created threads
---------------------------
-
-When threads are created using the dedicated Python APIs (such as the
-:mod:`threading` module), a thread state is automatically associated to them
-and the code showed above is therefore correct. However, when threads are
-created from C (for example by a third-party library with its own thread
-management), they don't hold the :term:`GIL`, because they don't have an
-:term:`attached thread state`.
-
-If you need to call Python code from these threads (often this will be part
-of a callback API provided by the aforementioned third-party library),
-you must first register these threads with the interpreter by
-creating an :term:`attached thread state` before you can start using the Python/C
-API. When you are done, you should detach the :term:`thread state `, and
-finally free it.
-
-The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do
-all of the above automatically. The typical idiom for calling into Python
-from a C thread is::
-
- PyGILState_STATE gstate;
- gstate = PyGILState_Ensure();
-
- /* Perform Python actions here. */
- result = CallSomeFunction();
- /* evaluate result or handle exception */
-
- /* Release the thread. No Python API allowed beyond this point. */
- PyGILState_Release(gstate);
-
-Note that the ``PyGILState_*`` functions assume there is only one global
-interpreter (created automatically by :c:func:`Py_Initialize`). Python
-supports the creation of additional interpreters (using
-:c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the
-``PyGILState_*`` API is unsupported. This is because :c:func:`PyGILState_Ensure`
-and similar functions default to :term:`attaching ` a
-:term:`thread state` for the main interpreter, meaning that the thread can't safely
-interact with the calling subinterpreter.
-
-Supporting subinterpreters in non-Python threads
-------------------------------------------------
-
-If you would like to support subinterpreters with non-Python created threads, you
-must use the ``PyThreadState_*`` API instead of the traditional ``PyGILState_*``
-API.
-
-In particular, you must store the interpreter state from the calling
-function and pass it to :c:func:`PyThreadState_New`, which will ensure that
-the :term:`thread state` is targeting the correct interpreter::
-
- /* The return value of PyInterpreterState_Get() from the
- function that created this thread. */
- PyInterpreterState *interp = ThreadData->interp;
- PyThreadState *tstate = PyThreadState_New(interp);
- PyThreadState_Swap(tstate);
-
- /* GIL of the subinterpreter is now held.
- Perform Python actions here. */
- result = CallSomeFunction();
- /* evaluate result or handle exception */
-
- /* Destroy the thread state. No Python API allowed beyond this point. */
- PyThreadState_Clear(tstate);
- PyThreadState_DeleteCurrent();
-
-.. _fork-and-threads:
-
-Cautions about fork()
----------------------
-
-Another important thing to note about threads is their behaviour in the face
-of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a
-process forks only the thread that issued the fork will exist. This has a
-concrete impact both on how locks must be handled and on all stored state
-in CPython's runtime.
-
-The fact that only the "current" thread remains
-means any locks held by other threads will never be released. Python solves
-this for :func:`os.fork` by acquiring the locks it uses internally before
-the fork, and releasing them afterwards. In addition, it resets any
-:ref:`lock-objects` in the child. When extending or embedding Python, there
-is no way to inform Python of additional (non-Python) locks that need to be
-acquired before or reset after a fork. OS facilities such as
-:c:func:`!pthread_atfork` would need to be used to accomplish the same thing.
-Additionally, when extending or embedding Python, calling :c:func:`fork`
-directly rather than through :func:`os.fork` (and returning to or calling
-into Python) may result in a deadlock by one of Python's internal locks
-being held by a thread that is defunct after the fork.
-:c:func:`PyOS_AfterFork_Child` tries to reset the necessary locks, but is not
-always able to.
-
-The fact that all other threads go away also means that CPython's
-runtime state there must be cleaned up properly, which :func:`os.fork`
-does. This means finalizing all other :c:type:`PyThreadState` objects
-belonging to the current interpreter and all other
-:c:type:`PyInterpreterState` objects. Due to this and the special
-nature of the :ref:`"main" interpreter `,
-:c:func:`fork` should only be called in that interpreter's "main"
-thread, where the CPython global runtime was originally initialized.
-The only exception is if :c:func:`exec` will be called immediately
-after.
-
-.. _cautions-regarding-runtime-finalization:
-
-Cautions regarding runtime finalization
----------------------------------------
-
-In the late stage of :term:`interpreter shutdown`, after attempting to wait for
-non-daemon threads to exit (though this can be interrupted by
-:class:`KeyboardInterrupt`) and running the :mod:`atexit` functions, the runtime
-is marked as *finalizing*: :c:func:`Py_IsFinalizing` and
-:func:`sys.is_finalizing` return true. At this point, only the *finalization
-thread* that initiated finalization (typically the main thread) is allowed to
-acquire the :term:`GIL`.
-
-If any thread, other than the finalization thread, attempts to attach a :term:`thread state`
-during finalization, either explicitly or
-implicitly, the thread enters **a permanently blocked state**
-where it remains until the program exits. In most cases this is harmless, but this can result
-in deadlock if a later stage of finalization attempts to acquire a lock owned by the
-blocked thread, or otherwise waits on the blocked thread.
-
-Gross? Yes. This prevents random crashes and/or unexpectedly skipped C++
-finalizations further up the call stack when such threads were forcibly exited
-here in CPython 3.13 and earlier. The CPython runtime :term:`thread state` C APIs
-have never had any error reporting or handling expectations at :term:`thread state`
-attachment time that would've allowed for graceful exit from this situation. Changing that
-would require new stable C APIs and rewriting the majority of C code in the
-CPython ecosystem to use those with error handling.
-
-
-High-level API
---------------
-
-These are the most commonly used types and functions when writing C extension
-code, or when embedding the Python interpreter:
-
-.. c:type:: PyInterpreterState
-
- This data structure represents the state shared by a number of cooperating
- threads. Threads belonging to the same interpreter share their module
- administration and a few other internal items. There are no public members in
- this structure.
-
- Threads belonging to different interpreters initially share nothing, except
- process state like available memory, open file descriptors and such. The global
- interpreter lock is also shared by all threads, regardless of to which
- interpreter they belong.
-
- .. versionchanged:: 3.12
-
- :pep:`684` introduced the possibility
- of a :ref:`per-interpreter GIL `.
- See :c:func:`Py_NewInterpreterFromConfig`.
-
-
-.. c:type:: PyThreadState
-
- This data structure represents the state of a single thread. The only public
- data member is:
-
- .. c:member:: PyInterpreterState *interp
-
- This thread's interpreter state.
-
-
-.. c:function:: void PyEval_InitThreads()
-
- .. index::
- single: PyEval_AcquireThread()
- single: PyEval_ReleaseThread()
- single: PyEval_SaveThread()
- single: PyEval_RestoreThread()
-
- Deprecated function which does nothing.
-
- In Python 3.6 and older, this function created the GIL if it didn't exist.
-
- .. versionchanged:: 3.9
- The function now does nothing.
-
- .. versionchanged:: 3.7
- This function is now called by :c:func:`Py_Initialize()`, so you don't
- have to call it yourself anymore.
-
- .. versionchanged:: 3.2
- This function cannot be called before :c:func:`Py_Initialize()` anymore.
-
- .. deprecated:: 3.9
-
- .. index:: pair: module; _thread
-
-
-.. c:function:: PyThreadState* PyEval_SaveThread()
-
- Detach the :term:`attached thread state` and return it.
- The thread will have no :term:`thread state` upon returning.
-
-
-.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate)
-
- Set the :term:`attached thread state` to *tstate*.
- The passed :term:`thread state` **should not** be :term:`attached `,
- otherwise deadlock ensues. *tstate* will be attached upon returning.
-
- .. note::
- Calling this function from a thread when the runtime is finalizing will
- hang the thread until the program exits, even if the thread was not
- created by Python. Refer to
- :ref:`cautions-regarding-runtime-finalization` for more details.
-
- .. versionchanged:: 3.14
- Hangs the current thread, rather than terminating it, if called while the
- interpreter is finalizing.
-
-.. c:function:: PyThreadState* PyThreadState_Get()
-
- Return the :term:`attached thread state`. If the thread has no attached
- thread state, (such as when inside of :c:macro:`Py_BEGIN_ALLOW_THREADS`
- block), then this issues a fatal error (so that the caller needn't check
- for ``NULL``).
-
- See also :c:func:`PyThreadState_GetUnchecked`.
-
-.. c:function:: PyThreadState* PyThreadState_GetUnchecked()
-
- Similar to :c:func:`PyThreadState_Get`, but don't kill the process with a
- fatal error if it is NULL. The caller is responsible to check if the result
- is NULL.
-
- .. versionadded:: 3.13
- In Python 3.5 to 3.12, the function was private and known as
- ``_PyThreadState_UncheckedGet()``.
-
-
-.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
-
- Set the :term:`attached thread state` to *tstate*, and return the
- :term:`thread state` that was attached prior to calling.
-
- This function is safe to call without an :term:`attached thread state`; it
- will simply return ``NULL`` indicating that there was no prior thread state.
-
- .. seealso::
- :c:func:`PyEval_ReleaseThread`
-
- .. note::
- Similar to :c:func:`PyGILState_Ensure`, this function will hang the
- thread if the runtime is finalizing.
-
-
-The following functions use thread-local storage, and are not compatible
-with sub-interpreters:
-
-.. c:type:: PyGILState_STATE
-
- The type of the value returned by :c:func:`PyGILState_Ensure` and passed to
- :c:func:`PyGILState_Release`.
-
- .. c:enumerator:: PyGILState_LOCKED
-
- The GIL was already held when :c:func:`PyGILState_Ensure` was called.
-
- .. c:enumerator:: PyGILState_UNLOCKED
-
- The GIL was not held when :c:func:`PyGILState_Ensure` was called.
-
-.. c:function:: PyGILState_STATE PyGILState_Ensure()
-
- Ensure that the current thread is ready to call the Python C API regardless
- of the current state of Python, or of the :term:`attached thread state`. This may
- be called as many times as desired by a thread as long as each call is
- matched with a call to :c:func:`PyGILState_Release`. In general, other
- thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
- :c:func:`PyGILState_Release` calls as long as the thread state is restored to
- its previous state before the Release(). For example, normal usage of the
- :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
- acceptable.
-
- The return value is an opaque "handle" to the :term:`attached thread state` when
- :c:func:`PyGILState_Ensure` was called, and must be passed to
- :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
- though recursive calls are allowed, these handles *cannot* be shared - each
- unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
- to :c:func:`PyGILState_Release`.
-
- When the function returns, there will be an :term:`attached thread state`
- and the thread will be able to call arbitrary Python code. Failure is a fatal error.
-
- .. warning::
- Calling this function when the runtime is finalizing is unsafe. Doing
- so will either hang the thread until the program ends, or fully crash
- the interpreter in rare cases. Refer to
- :ref:`cautions-regarding-runtime-finalization` for more details.
-
- .. versionchanged:: 3.14
- Hangs the current thread, rather than terminating it, if called while the
- interpreter is finalizing.
-
-.. c:function:: void PyGILState_Release(PyGILState_STATE)
-
- Release any resources previously acquired. After this call, Python's state will
- be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
- (but generally this state will be unknown to the caller, hence the use of the
- GILState API).
-
- Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
- :c:func:`PyGILState_Release` on the same thread.
-
-.. c:function:: PyThreadState* PyGILState_GetThisThreadState()
-
- Get the :term:`attached thread state` for this thread. May return ``NULL`` if no
- GILState API has been used on the current thread. Note that the main thread
- always has such a thread-state, even if no auto-thread-state call has been
- made on the main thread. This is mainly a helper/diagnostic function.
-
- .. note::
- This function may return non-``NULL`` even when the :term:`thread state`
- is detached.
- Prefer :c:func:`PyThreadState_Get` or :c:func:`PyThreadState_GetUnchecked`
- for most cases.
-
- .. seealso:: :c:func:`PyThreadState_Get`
-
-.. c:function:: int PyGILState_Check()
-
- Return ``1`` if the current thread is holding the :term:`GIL` and ``0`` otherwise.
- This function can be called from any thread at any time.
- Only if it has had its :term:`thread state ` initialized
- via :c:func:`PyGILState_Ensure` will it return ``1``.
- This is mainly a helper/diagnostic function. It can be useful
- for example in callback contexts or memory allocation functions when
- knowing that the :term:`GIL` is locked can allow the caller to perform sensitive
- actions or otherwise behave differently.
-
- .. note::
- If the current Python process has ever created a subinterpreter, this
- function will *always* return ``1``. Prefer :c:func:`PyThreadState_GetUnchecked`
- for most cases.
-
- .. versionadded:: 3.4
-
-
-The following macros are normally used without a trailing semicolon; look for
-example usage in the Python source distribution.
-
-
-.. c:macro:: Py_BEGIN_ALLOW_THREADS
-
- This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
- Note that it contains an opening brace; it must be matched with a following
- :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
- macro.
-
-
-.. c:macro:: Py_END_ALLOW_THREADS
-
- This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
- a closing brace; it must be matched with an earlier
- :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
- this macro.
-
-
-.. c:macro:: Py_BLOCK_THREADS
-
- This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
- :c:macro:`Py_END_ALLOW_THREADS` without the closing brace.
-
-
-.. c:macro:: Py_UNBLOCK_THREADS
-
- This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
- :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
- declaration.
-
-
-Low-level API
--------------
-
-All of the following functions must be called after :c:func:`Py_Initialize`.
-
-.. versionchanged:: 3.7
- :c:func:`Py_Initialize()` now initializes the :term:`GIL`
- and sets an :term:`attached thread state`.
-
-
-.. c:function:: PyInterpreterState* PyInterpreterState_New()
-
- Create a new interpreter state object. An :term:`attached thread state` is not needed,
- but may optionally exist if it is necessary to serialize calls to this
- function.
-
- .. audit-event:: cpython.PyInterpreterState_New "" c.PyInterpreterState_New
-
-
-.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp)
-
- Reset all information in an interpreter state object. There must be
- an :term:`attached thread state` for the interpreter.
-
- .. audit-event:: cpython.PyInterpreterState_Clear "" c.PyInterpreterState_Clear
-
-
-.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp)
-
- Destroy an interpreter state object. There **should not** be an
- :term:`attached thread state` for the target interpreter. The interpreter
- state must have been reset with a previous call to :c:func:`PyInterpreterState_Clear`.
-
-
-.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
-
- Create a new thread state object belonging to the given interpreter object.
- An :term:`attached thread state` is not needed.
-
-.. c:function:: void PyThreadState_Clear(PyThreadState *tstate)
-
- Reset all information in a :term:`thread state` object. *tstate*
- must be :term:`attached `
-
- .. versionchanged:: 3.9
- This function now calls the :c:member:`!PyThreadState.on_delete` callback.
- Previously, that happened in :c:func:`PyThreadState_Delete`.
-
- .. versionchanged:: 3.13
- The :c:member:`!PyThreadState.on_delete` callback was removed.
-
-
-.. c:function:: void PyThreadState_Delete(PyThreadState *tstate)
-
- Destroy a :term:`thread state` object. *tstate* should not
- be :term:`attached ` to any thread.
- *tstate* must have been reset with a previous call to
- :c:func:`PyThreadState_Clear`.
-
-
-.. c:function:: void PyThreadState_DeleteCurrent(void)
-
- Detach the :term:`attached thread state` (which must have been reset
- with a previous call to :c:func:`PyThreadState_Clear`) and then destroy it.
-
- No :term:`thread state` will be :term:`attached ` upon
- returning.
-
-.. c:function:: PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)
-
- Get the current frame of the Python thread state *tstate*.
-
- Return a :term:`strong reference`. Return ``NULL`` if no frame is currently
- executing.
-
- See also :c:func:`PyEval_GetFrame`.
-
- *tstate* must not be ``NULL``, and must be :term:`attached `.
-
- .. versionadded:: 3.9
-
-
-.. c:function:: uint64_t PyThreadState_GetID(PyThreadState *tstate)
-
- Get the unique :term:`thread state` identifier of the Python thread state *tstate*.
-
- *tstate* must not be ``NULL``, and must be :term:`attached `.
-
- .. versionadded:: 3.9
-
-
-.. c:function:: PyInterpreterState* PyThreadState_GetInterpreter(PyThreadState *tstate)
-
- Get the interpreter of the Python thread state *tstate*.
-
- *tstate* must not be ``NULL``, and must be :term:`attached `.
-
- .. versionadded:: 3.9
-
-
-.. c:function:: void PyThreadState_EnterTracing(PyThreadState *tstate)
-
- Suspend tracing and profiling in the Python thread state *tstate*.
-
- Resume them using the :c:func:`PyThreadState_LeaveTracing` function.
-
- .. versionadded:: 3.11
-
-
-.. c:function:: void PyThreadState_LeaveTracing(PyThreadState *tstate)
-
- Resume tracing and profiling in the Python thread state *tstate* suspended
- by the :c:func:`PyThreadState_EnterTracing` function.
-
- See also :c:func:`PyEval_SetTrace` and :c:func:`PyEval_SetProfile`
- functions.
-
- .. versionadded:: 3.11
-
-
-.. c:function:: int PyUnstable_ThreadState_SetStackProtection(PyThreadState *tstate, void *stack_start_addr, size_t stack_size)
-
- Set the stack protection start address and stack protection size
- of a Python thread state.
-
- On success, return ``0``.
- On failure, set an exception and return ``-1``.
-
- CPython implements :ref:`recursion control ` for C code by raising
- :py:exc:`RecursionError` when it notices that the machine execution stack is close
- to overflow. See for example the :c:func:`Py_EnterRecursiveCall` function.
- For this, it needs to know the location of the current thread's stack, which it
- normally gets from the operating system.
- When the stack is changed, for example using context switching techniques like the
- Boost library's ``boost::context``, you must call
- :c:func:`~PyUnstable_ThreadState_SetStackProtection` to inform CPython of the change.
-
- Call :c:func:`~PyUnstable_ThreadState_SetStackProtection` either before
- or after changing the stack.
- Do not call any other Python C API between the call and the stack
- change.
-
- See :c:func:`PyUnstable_ThreadState_ResetStackProtection` for undoing this operation.
-
- .. versionadded:: 3.15
-
-
-.. c:function:: void PyUnstable_ThreadState_ResetStackProtection(PyThreadState *tstate)
-
- Reset the stack protection start address and stack protection size
- of a Python thread state to the operating system defaults.
-
- See :c:func:`PyUnstable_ThreadState_SetStackProtection` for an explanation.
-
- .. versionadded:: 3.15
-
-
-.. c:function:: PyInterpreterState* PyInterpreterState_Get(void)
-
- Get the current interpreter.
-
- Issue a fatal error if there no :term:`attached thread state`.
- It cannot return NULL.
-
- .. versionadded:: 3.9
-
-
-.. c:function:: int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
-
- Return the interpreter's unique ID. If there was any error in doing
- so then ``-1`` is returned and an error is set.
-
- The caller must have an :term:`attached thread state`.
-
- .. versionadded:: 3.7
-
-
-.. c:function:: PyObject* PyInterpreterState_GetDict(PyInterpreterState *interp)
-
- Return a dictionary in which interpreter-specific data may be stored.
- If this function returns ``NULL`` then no exception has been raised and
- the caller should assume no interpreter-specific dict is available.
-
- This is not a replacement for :c:func:`PyModule_GetState()`, which
- extensions should use to store interpreter-specific state information.
-
- The returned dictionary is borrowed from the interpreter and is valid until
- interpreter shutdown.
-
- .. versionadded:: 3.8
-
-
-.. c:type:: PyObject* (*_PyFrameEvalFunction)(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)
-
- Type of a frame evaluation function.
-
- The *throwflag* parameter is used by the ``throw()`` method of generators:
- if non-zero, handle the current exception.
-
- .. versionchanged:: 3.9
- The function now takes a *tstate* parameter.
-
- .. versionchanged:: 3.11
- The *frame* parameter changed from ``PyFrameObject*`` to ``_PyInterpreterFrame*``.
-
-.. c:function:: _PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
-
- Get the frame evaluation function.
-
- See the :pep:`523` "Adding a frame evaluation API to CPython".
-
- .. versionadded:: 3.9
-
-.. c:function:: void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)
-
- Set the frame evaluation function.
-
- See the :pep:`523` "Adding a frame evaluation API to CPython".
-
- .. versionadded:: 3.9
-
-
-.. c:function:: PyObject* PyThreadState_GetDict()
-
- Return a dictionary in which extensions can store thread-specific state
- information. Each extension should use a unique key to use to store state in
- the dictionary. It is okay to call this function when no :term:`thread state`
- is :term:`attached `. If this function returns
- ``NULL``, no exception has been raised and the caller should assume no
- thread state is attached.
-
-
-.. c:function:: int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
-
- Asynchronously raise an exception in a thread. The *id* argument is the thread
- id of the target thread; *exc* is the exception object to be raised. This
- function does not steal any references to *exc*. To prevent naive misuse, you
- must write your own C extension to call this. Must be called with an :term:`attached thread state`.
- Returns the number of thread states modified; this is normally one, but will be
- zero if the thread id isn't found. If *exc* is ``NULL``, the pending
- exception (if any) for the thread is cleared. This raises no exceptions.
-
- .. versionchanged:: 3.7
- The type of the *id* parameter changed from :c:expr:`long` to
- :c:expr:`unsigned long`.
-
-.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)
-
- :term:`Attach ` *tstate* to the current thread,
- which must not be ``NULL`` or already :term:`attached `.
-
- The calling thread must not already have an :term:`attached thread state`.
-
- .. note::
- Calling this function from a thread when the runtime is finalizing will
- hang the thread until the program exits, even if the thread was not
- created by Python. Refer to
- :ref:`cautions-regarding-runtime-finalization` for more details.
-
- .. versionchanged:: 3.8
- Updated to be consistent with :c:func:`PyEval_RestoreThread`,
- :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`,
- and terminate the current thread if called while the interpreter is finalizing.
-
- .. versionchanged:: 3.14
- Hangs the current thread, rather than terminating it, if called while the
- interpreter is finalizing.
-
- :c:func:`PyEval_RestoreThread` is a higher-level function which is always
- available (even when threads have not been initialized).
-
-
-.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)
-
- Detach the :term:`attached thread state`.
- The *tstate* argument, which must not be ``NULL``, is only used to check
- that it represents the :term:`attached thread state` --- if it isn't, a fatal error is
- reported.
-
- :c:func:`PyEval_SaveThread` is a higher-level function which is always
- available (even when threads have not been initialized).
-
-
-.. _sub-interpreter-support:
-
-Sub-interpreter support
-=======================
-
-While in most uses, you will only embed a single Python interpreter, there
-are cases where you need to create several independent interpreters in the
-same process and perhaps even in the same thread. Sub-interpreters allow
-you to do that.
-
-The "main" interpreter is the first one created when the runtime initializes.
-It is usually the only Python interpreter in a process. Unlike sub-interpreters,
-the main interpreter has unique process-global responsibilities like signal
-handling. It is also responsible for execution during runtime initialization and
-is usually the active interpreter during runtime finalization. The
-:c:func:`PyInterpreterState_Main` function returns a pointer to its state.
-
-You can switch between sub-interpreters using the :c:func:`PyThreadState_Swap`
-function. You can create and destroy them using the following functions:
-
-
-.. c:type:: PyInterpreterConfig
-
- Structure containing most parameters to configure a sub-interpreter.
- Its values are used only in :c:func:`Py_NewInterpreterFromConfig` and
- never modified by the runtime.
-
- .. versionadded:: 3.12
-
- Structure fields:
-
- .. c:member:: int use_main_obmalloc
-
- If this is ``0`` then the sub-interpreter will use its own
- "object" allocator state.
- Otherwise it will use (share) the main interpreter's.
-
- If this is ``0`` then
- :c:member:`~PyInterpreterConfig.check_multi_interp_extensions`
- must be ``1`` (non-zero).
- If this is ``1`` then :c:member:`~PyInterpreterConfig.gil`
- must not be :c:macro:`PyInterpreterConfig_OWN_GIL`.
-
- .. c:member:: int allow_fork
-
- If this is ``0`` then the runtime will not support forking the
- process in any thread where the sub-interpreter is currently active.
- Otherwise fork is unrestricted.
-
- Note that the :mod:`subprocess` module still works
- when fork is disallowed.
-
- .. c:member:: int allow_exec
-
- If this is ``0`` then the runtime will not support replacing the
- current process via exec (e.g. :func:`os.execv`) in any thread
- where the sub-interpreter is currently active.
- Otherwise exec is unrestricted.
-
- Note that the :mod:`subprocess` module still works
- when exec is disallowed.
-
- .. c:member:: int allow_threads
-
- If this is ``0`` then the sub-interpreter's :mod:`threading` module
- won't create threads.
- Otherwise threads are allowed.
-
- .. c:member:: int allow_daemon_threads
-
- If this is ``0`` then the sub-interpreter's :mod:`threading` module
- won't create daemon threads.
- Otherwise daemon threads are allowed (as long as
- :c:member:`~PyInterpreterConfig.allow_threads` is non-zero).
-
- .. c:member:: int check_multi_interp_extensions
-
- If this is ``0`` then all extension modules may be imported,
- including legacy (single-phase init) modules,
- in any thread where the sub-interpreter is currently active.
- Otherwise only multi-phase init extension modules
- (see :pep:`489`) may be imported.
- (Also see :c:macro:`Py_mod_multiple_interpreters`.)
-
- This must be ``1`` (non-zero) if
- :c:member:`~PyInterpreterConfig.use_main_obmalloc` is ``0``.
-
- .. c:member:: int gil
-
- This determines the operation of the GIL for the sub-interpreter.
- It may be one of the following:
-
- .. c:namespace:: NULL
-
- .. c:macro:: PyInterpreterConfig_DEFAULT_GIL
-
- Use the default selection (:c:macro:`PyInterpreterConfig_SHARED_GIL`).
-
- .. c:macro:: PyInterpreterConfig_SHARED_GIL
-
- Use (share) the main interpreter's GIL.
-
- .. c:macro:: PyInterpreterConfig_OWN_GIL
-
- Use the sub-interpreter's own GIL.
-
- If this is :c:macro:`PyInterpreterConfig_OWN_GIL` then
- :c:member:`PyInterpreterConfig.use_main_obmalloc` must be ``0``.
-
-
-.. c:function:: PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)
-
- .. index::
- pair: module; builtins
- pair: module; __main__
- pair: module; sys
- single: stdout (in module sys)
- single: stderr (in module sys)
- single: stdin (in module sys)
-
- Create a new sub-interpreter. This is an (almost) totally separate environment
- for the execution of Python code. In particular, the new interpreter has
- separate, independent versions of all imported modules, including the
- fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The
- table of loaded modules (``sys.modules``) and the module search path
- (``sys.path``) are also separate. The new environment has no ``sys.argv``
- variable. It has new standard I/O stream file objects ``sys.stdin``,
- ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
- file descriptors).
-
- The given *config* controls the options with which the interpreter
- is initialized.
-
- Upon success, *tstate_p* will be set to the first :term:`thread state`
- created in the new sub-interpreter. This thread state is
- :term:`attached `.
- Note that no actual thread is created; see the discussion of thread states
- below. If creation of the new interpreter is unsuccessful,
- *tstate_p* is set to ``NULL``;
- no exception is set since the exception state is stored in the
- :term:`attached thread state`, which might not exist.
-
- Like all other Python/C API functions, an :term:`attached thread state`
- must be present before calling this function, but it might be detached upon
- returning. On success, the returned thread state will be :term:`attached `.
- If the sub-interpreter is created with its own :term:`GIL` then the
- :term:`attached thread state` of the calling interpreter will be detached.
- When the function returns, the new interpreter's :term:`thread state`
- will be :term:`attached ` to the current thread and
- the previous interpreter's :term:`attached thread state` will remain detached.
-
- .. versionadded:: 3.12
-
- Sub-interpreters are most effective when isolated from each other,
- with certain functionality restricted::
-
- PyInterpreterConfig config = {
- .use_main_obmalloc = 0,
- .allow_fork = 0,
- .allow_exec = 0,
- .allow_threads = 1,
- .allow_daemon_threads = 0,
- .check_multi_interp_extensions = 1,
- .gil = PyInterpreterConfig_OWN_GIL,
- };
- PyThreadState *tstate = NULL;
- PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
- if (PyStatus_Exception(status)) {
- Py_ExitStatusException(status);
- }
-
- Note that the config is used only briefly and does not get modified.
- During initialization the config's values are converted into various
- :c:type:`PyInterpreterState` values. A read-only copy of the config
- may be stored internally on the :c:type:`PyInterpreterState`.
-
- .. index::
- single: Py_FinalizeEx (C function)
- single: Py_Initialize (C function)
-
- Extension modules are shared between (sub-)interpreters as follows:
-
- * For modules using multi-phase initialization,
- e.g. :c:func:`PyModule_FromDefAndSpec`, a separate module object is
- created and initialized for each interpreter.
- Only C-level static and global variables are shared between these
- module objects.
-
- * For modules using legacy
- :ref:`single-phase initialization `,
- e.g. :c:func:`PyModule_Create`, the first time a particular extension
- is imported, it is initialized normally, and a (shallow) copy of its
- module's dictionary is squirreled away.
- When the same extension is imported by another (sub-)interpreter, a new
- module is initialized and filled with the contents of this copy; the
- extension's ``init`` function is not called.
- Objects in the module's dictionary thus end up shared across
- (sub-)interpreters, which might cause unwanted behavior (see
- `Bugs and caveats`_ below).
-
- Note that this is different from what happens when an extension is
- imported after the interpreter has been completely re-initialized by
- calling :c:func:`Py_FinalizeEx` and :c:func:`Py_Initialize`; in that
- case, the extension's ``initmodule`` function *is* called again.
- As with multi-phase initialization, this means that only C-level static
- and global variables are shared between these modules.
-
- .. index:: single: close (in module os)
-
-
-.. c:function:: PyThreadState* Py_NewInterpreter(void)
-
- .. index::
- pair: module; builtins
- pair: module; __main__
- pair: module; sys
- single: stdout (in module sys)
- single: stderr (in module sys)
- single: stdin (in module sys)
-
- Create a new sub-interpreter. This is essentially just a wrapper
- around :c:func:`Py_NewInterpreterFromConfig` with a config that
- preserves the existing behavior. The result is an unisolated
- sub-interpreter that shares the main interpreter's GIL, allows
- fork/exec, allows daemon threads, and allows single-phase init
- modules.
-
-
-.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
-
- .. index:: single: Py_FinalizeEx (C function)
-
- Destroy the (sub-)interpreter represented by the given :term:`thread state`.
- The given thread state must be :term:`attached `.
- When the call returns, there will be no :term:`attached thread state`.
- All thread states associated with this interpreter are destroyed.
-
- :c:func:`Py_FinalizeEx` will destroy all sub-interpreters that
- haven't been explicitly destroyed at that point.
-
-
-.. _per-interpreter-gil:
-
-A Per-Interpreter GIL
----------------------
-
-Using :c:func:`Py_NewInterpreterFromConfig` you can create
-a sub-interpreter that is completely isolated from other interpreters,
-including having its own GIL. The most important benefit of this
-isolation is that such an interpreter can execute Python code without
-being blocked by other interpreters or blocking any others. Thus a
-single Python process can truly take advantage of multiple CPU cores
-when running Python code. The isolation also encourages a different
-approach to concurrency than that of just using threads.
-(See :pep:`554` and :pep:`684`.)
-
-Using an isolated interpreter requires vigilance in preserving that
-isolation. That especially means not sharing any objects or mutable
-state without guarantees about thread-safety. Even objects that are
-otherwise immutable (e.g. ``None``, ``(1, 5)``) can't normally be shared
-because of the refcount. One simple but less-efficient approach around
-this is to use a global lock around all use of some state (or object).
-Alternately, effectively immutable objects (like integers or strings)
-can be made safe in spite of their refcounts by making them :term:`immortal`.
-In fact, this has been done for the builtin singletons, small integers,
-and a number of other builtin objects.
-
-If you preserve isolation then you will have access to proper multi-core
-computing without the complications that come with free-threading.
-Failure to preserve isolation will expose you to the full consequences
-of free-threading, including races and hard-to-debug crashes.
-
-Aside from that, one of the main challenges of using multiple isolated
-interpreters is how to communicate between them safely (not break
-isolation) and efficiently. The runtime and stdlib do not provide
-any standard approach to this yet. A future stdlib module would help
-mitigate the effort of preserving isolation and expose effective tools
-for communicating (and sharing) data between interpreters.
-
-.. versionadded:: 3.12
-
-
-Bugs and caveats
-----------------
-
-Because sub-interpreters (and the main interpreter) are part of the same
-process, the insulation between them isn't perfect --- for example, using
-low-level file operations like :func:`os.close` they can
-(accidentally or maliciously) affect each other's open files. Because of the
-way extensions are shared between (sub-)interpreters, some extensions may not
-work properly; this is especially likely when using single-phase initialization
-or (static) global variables.
-It is possible to insert objects created in one sub-interpreter into
-a namespace of another (sub-)interpreter; this should be avoided if possible.
-
-Special care should be taken to avoid sharing user-defined functions,
-methods, instances or classes between sub-interpreters, since import
-operations executed by such objects may affect the wrong (sub-)interpreter's
-dictionary of loaded modules. It is equally important to avoid sharing
-objects from which the above are reachable.
-
-Also note that combining this functionality with ``PyGILState_*`` APIs
-is delicate, because these APIs assume a bijection between Python thread states
-and OS-level threads, an assumption broken by the presence of sub-interpreters.
-It is highly recommended that you don't switch sub-interpreters between a pair
-of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
-Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
-of Python code from non-Python created threads will probably be broken when using
-sub-interpreters.
-
-
-Asynchronous Notifications
-==========================
-
-A mechanism is provided to make asynchronous notifications to the main
-interpreter thread. These notifications take the form of a function
-pointer and a void pointer argument.
-
-
-.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)
-
- Schedule a function to be called from the main interpreter thread. On
- success, ``0`` is returned and *func* is queued for being called in the
- main thread. On failure, ``-1`` is returned without setting any exception.
-
- When successfully queued, *func* will be *eventually* called from the
- main interpreter thread with the argument *arg*. It will be called
- asynchronously with respect to normally running Python code, but with
- both these conditions met:
-
- * on a :term:`bytecode` boundary;
- * with the main thread holding an :term:`attached thread state`
- (*func* can therefore use the full C API).
-
- *func* must return ``0`` on success, or ``-1`` on failure with an exception
- set. *func* won't be interrupted to perform another asynchronous
- notification recursively, but it can still be interrupted to switch
- threads if the :term:`thread state ` is detached.
-
- This function doesn't need an :term:`attached thread state`. However, to call this
- function in a subinterpreter, the caller must have an :term:`attached thread state`.
- Otherwise, the function *func* can be scheduled to be called from the wrong interpreter.
-
- .. warning::
- This is a low-level function, only useful for very special cases.
- There is no guarantee that *func* will be called as quick as
- possible. If the main thread is busy executing a system call,
- *func* won't be called before the system call returns. This
- function is generally **not** suitable for calling Python code from
- arbitrary C threads. Instead, use the :ref:`PyGILState API`.
-
- .. versionadded:: 3.1
-
- .. versionchanged:: 3.9
- If this function is called in a subinterpreter, the function *func* is
- now scheduled to be called from the subinterpreter, rather than being
- called from the main interpreter. Each subinterpreter now has its own
- list of scheduled calls.
-
- .. versionchanged:: 3.12
- This function now always schedules *func* to be run in the main
- interpreter.
-
-
-.. c:function:: int Py_MakePendingCalls(void)
-
- Execute all pending calls. This is usually executed automatically by the
- interpreter.
-
- This function returns ``0`` on success, and returns ``-1`` with an exception
- set on failure.
-
- If this is not called in the main thread of the main
- interpreter, this function does nothing and returns ``0``.
- The caller must hold an :term:`attached thread state`.
-
- .. versionadded:: 3.1
-
- .. versionchanged:: 3.12
- This function only runs pending calls in the main interpreter.
-
-
-.. _profiling:
-
-Profiling and Tracing
-=====================
-
-.. sectionauthor:: Fred L. Drake, Jr.
-
-
-The Python interpreter provides some low-level support for attaching profiling
-and execution tracing facilities. These are used for profiling, debugging, and
-coverage analysis tools.
-
-This C interface allows the profiling or tracing code to avoid the overhead of
-calling through Python-level callable objects, making a direct C function call
-instead. The essential attributes of the facility have not changed; the
-interface allows trace functions to be installed per-thread, and the basic
-events reported to the trace function are the same as had been reported to the
-Python-level trace functions in previous versions.
-
-
-.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
-
- The type of the trace function registered using :c:func:`PyEval_SetProfile` and
- :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the
- registration function as *obj*, *frame* is the frame object to which the event
- pertains, *what* is one of the constants :c:data:`PyTrace_CALL`,
- :c:data:`PyTrace_EXCEPTION`, :c:data:`PyTrace_LINE`, :c:data:`PyTrace_RETURN`,
- :c:data:`PyTrace_C_CALL`, :c:data:`PyTrace_C_EXCEPTION`, :c:data:`PyTrace_C_RETURN`,
- or :c:data:`PyTrace_OPCODE`, and *arg* depends on the value of *what*:
-
- +-------------------------------+----------------------------------------+
- | Value of *what* | Meaning of *arg* |
- +===============================+========================================+
- | :c:data:`PyTrace_CALL` | Always :c:data:`Py_None`. |
- +-------------------------------+----------------------------------------+
- | :c:data:`PyTrace_EXCEPTION` | Exception information as returned by |
- | | :func:`sys.exc_info`. |
- +-------------------------------+----------------------------------------+
- | :c:data:`PyTrace_LINE` | Always :c:data:`Py_None`. |
- +-------------------------------+----------------------------------------+
- | :c:data:`PyTrace_RETURN` | Value being returned to the caller, |
- | | or ``NULL`` if caused by an exception. |
- +-------------------------------+----------------------------------------+
- | :c:data:`PyTrace_C_CALL` | Function object being called. |
- +-------------------------------+----------------------------------------+
- | :c:data:`PyTrace_C_EXCEPTION` | Function object being called. |
- +-------------------------------+----------------------------------------+
- | :c:data:`PyTrace_C_RETURN` | Function object being called. |
- +-------------------------------+----------------------------------------+
- | :c:data:`PyTrace_OPCODE` | Always :c:data:`Py_None`. |
- +-------------------------------+----------------------------------------+
-
-.. c:var:: int PyTrace_CALL
-
- The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new
- call to a function or method is being reported, or a new entry into a generator.
- Note that the creation of the iterator for a generator function is not reported
- as there is no control transfer to the Python bytecode in the corresponding
- frame.
-
-
-.. c:var:: int PyTrace_EXCEPTION
-
- The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an
- exception has been raised. The callback function is called with this value for
- *what* when after any bytecode is processed after which the exception becomes
- set within the frame being executed. The effect of this is that as exception
- propagation causes the Python stack to unwind, the callback is called upon
- return to each frame as the exception propagates. Only trace functions receives
- these events; they are not needed by the profiler.
-
-
-.. c:var:: int PyTrace_LINE
-
- The value passed as the *what* parameter to a :c:type:`Py_tracefunc` function
- (but not a profiling function) when a line-number event is being reported.
- It may be disabled for a frame by setting :attr:`~frame.f_trace_lines` to
- *0* on that frame.
-
-
-.. c:var:: int PyTrace_RETURN
-
- The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a
- call is about to return.
-
-
-.. c:var:: int PyTrace_C_CALL
-
- The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
- function is about to be called.
-
-
-.. c:var:: int PyTrace_C_EXCEPTION
-
- The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
- function has raised an exception.
-
-
-.. c:var:: int PyTrace_C_RETURN
-
- The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
- function has returned.
-
-
-.. c:var:: int PyTrace_OPCODE
-
- The value for the *what* parameter to :c:type:`Py_tracefunc` functions (but not
- profiling functions) when a new opcode is about to be executed. This event is
- not emitted by default: it must be explicitly requested by setting
- :attr:`~frame.f_trace_opcodes` to *1* on the frame.
-
-
-.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
-
- Set the profiler function to *func*. The *obj* parameter is passed to the
- function as its first parameter, and may be any Python object, or ``NULL``. If
- the profile function needs to maintain state, using a different value for *obj*
- for each thread provides a convenient and thread-safe place to store it. The
- profile function is called for all monitored events except :c:data:`PyTrace_LINE`
- :c:data:`PyTrace_OPCODE` and :c:data:`PyTrace_EXCEPTION`.
-
- See also the :func:`sys.setprofile` function.
-
- The caller must have an :term:`attached thread state`.
-
-.. c:function:: void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)
-
- Like :c:func:`PyEval_SetProfile` but sets the profile function in all running threads
- belonging to the current interpreter instead of the setting it only on the current thread.
-
- The caller must have an :term:`attached thread state`.
-
- As :c:func:`PyEval_SetProfile`, this function ignores any exceptions raised while
- setting the profile functions in all threads.
-
-.. versionadded:: 3.12
-
-
-.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
-
- Set the tracing function to *func*. This is similar to
- :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number
- events and per-opcode events, but does not receive any event related to C function
- objects being called. Any trace function registered using :c:func:`PyEval_SetTrace`
- will not receive :c:data:`PyTrace_C_CALL`, :c:data:`PyTrace_C_EXCEPTION` or
- :c:data:`PyTrace_C_RETURN` as a value for the *what* parameter.
-
- See also the :func:`sys.settrace` function.
-
- The caller must have an :term:`attached thread state`.
-
-.. c:function:: void PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *obj)
-
- Like :c:func:`PyEval_SetTrace` but sets the tracing function in all running threads
- belonging to the current interpreter instead of the setting it only on the current thread.
-
- The caller must have an :term:`attached thread state`.
-
- As :c:func:`PyEval_SetTrace`, this function ignores any exceptions raised while
- setting the trace functions in all threads.
-
-.. versionadded:: 3.12
-
-Reference tracing
-=================
-
-.. versionadded:: 3.13
-
-.. c:type:: int (*PyRefTracer)(PyObject *, int event, void* data)
-
- The type of the trace function registered using :c:func:`PyRefTracer_SetTracer`.
- The first parameter is a Python object that has been just created (when **event**
- is set to :c:data:`PyRefTracer_CREATE`) or about to be destroyed (when **event**
- is set to :c:data:`PyRefTracer_DESTROY`). The **data** argument is the opaque pointer
- that was provided when :c:func:`PyRefTracer_SetTracer` was called.
-
- If a new tracing function is registered replacing the current a call to the
- trace function will be made with the object set to **NULL** and **event** set to
- :c:data:`PyRefTracer_TRACKER_REMOVED`. This will happen just before the new
- function is registered.
-
-.. versionadded:: 3.13
-
-.. c:var:: int PyRefTracer_CREATE
-
- The value for the *event* parameter to :c:type:`PyRefTracer` functions when a Python
- object has been created.
-
-.. c:var:: int PyRefTracer_DESTROY
-
- The value for the *event* parameter to :c:type:`PyRefTracer` functions when a Python
- object has been destroyed.
-
-.. c:var:: int PyRefTracer_TRACKER_REMOVED
-
- The value for the *event* parameter to :c:type:`PyRefTracer` functions when the
- current tracer is about to be replaced by a new one.
-
- .. versionadded:: 3.14
-
-.. c:function:: int PyRefTracer_SetTracer(PyRefTracer tracer, void *data)
-
- Register a reference tracer function. The function will be called when a new
- Python has been created or when an object is going to be destroyed. If
- **data** is provided it must be an opaque pointer that will be provided when
- the tracer function is called. Return ``0`` on success. Set an exception and
- return ``-1`` on error.
-
- Not that tracer functions **must not** create Python objects inside or
- otherwise the call will be re-entrant. The tracer also **must not** clear
- any existing exception or set an exception. A :term:`thread state` will be active
- every time the tracer function is called.
-
- There must be an :term:`attached thread state` when calling this function.
-
- If another tracer function was already registered, the old function will be
- called with **event** set to :c:data:`PyRefTracer_TRACKER_REMOVED` just before
- the new function is registered.
-
-.. versionadded:: 3.13
-
-.. c:function:: PyRefTracer PyRefTracer_GetTracer(void** data)
-
- Get the registered reference tracer function and the value of the opaque data
- pointer that was registered when :c:func:`PyRefTracer_SetTracer` was called.
- If no tracer was registered this function will return NULL and will set the
- **data** pointer to NULL.
-
- There must be an :term:`attached thread state` when calling this function.
-
-.. versionadded:: 3.13
-
-.. _advanced-debugging:
-
-Advanced Debugger Support
-=========================
-
-.. sectionauthor:: Fred L. Drake, Jr.
-
-
-These functions are only intended to be used by advanced debugging tools.
-
-
-.. c:function:: PyInterpreterState* PyInterpreterState_Head()
-
- Return the interpreter state object at the head of the list of all such objects.
-
-
-.. c:function:: PyInterpreterState* PyInterpreterState_Main()
-
- Return the main interpreter state object.
-
-
-.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
-
- Return the next interpreter state object after *interp* from the list of all
- such objects.
-
-
-.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
-
- Return the pointer to the first :c:type:`PyThreadState` object in the list of
- threads associated with the interpreter *interp*.
-
-
-.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
-
- Return the next thread state object after *tstate* from the list of all such
- objects belonging to the same :c:type:`PyInterpreterState` object.
-
-
-.. _thread-local-storage:
-
-Thread Local Storage Support
-============================
-
-.. sectionauthor:: Masayuki Yamamoto
-
-The Python interpreter provides low-level support for thread-local storage
-(TLS) which wraps the underlying native TLS implementation to support the
-Python-level thread local storage API (:class:`threading.local`). The
-CPython C level APIs are similar to those offered by pthreads and Windows:
-use a thread key and functions to associate a :c:expr:`void*` value per
-thread.
-
-A :term:`thread state` does *not* need to be :term:`attached `
-when calling these functions; they supply their own locking.
-
-Note that :file:`Python.h` does not include the declaration of the TLS APIs,
-you need to include :file:`pythread.h` to use thread-local storage.
-
-.. note::
- None of these API functions handle memory management on behalf of the
- :c:expr:`void*` values. You need to allocate and deallocate them yourself.
- If the :c:expr:`void*` values happen to be :c:expr:`PyObject*`, these
- functions don't do refcount operations on them either.
-
-.. _thread-specific-storage-api:
-
-Thread Specific Storage (TSS) API
----------------------------------
-
-TSS API is introduced to supersede the use of the existing TLS API within the
-CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of
-:c:expr:`int` to represent thread keys.
-
-.. versionadded:: 3.7
-
-.. seealso:: "A New C-API for Thread-Local Storage in CPython" (:pep:`539`)
-
-
-.. c:type:: Py_tss_t
-
- This data structure represents the state of a thread key, the definition of
- which may depend on the underlying TLS implementation, and it has an
- internal field representing the key's initialization state. There are no
- public members in this structure.
-
- When :ref:`Py_LIMITED_API ` is not defined, static allocation of
- this type by :c:macro:`Py_tss_NEEDS_INIT` is allowed.
-
-
-.. c:macro:: Py_tss_NEEDS_INIT
-
- This macro expands to the initializer for :c:type:`Py_tss_t` variables.
- Note that this macro won't be defined with :ref:`Py_LIMITED_API `.
-
-
-Dynamic Allocation
-~~~~~~~~~~~~~~~~~~
-
-Dynamic allocation of the :c:type:`Py_tss_t`, required in extension modules
-built with :ref:`Py_LIMITED_API `, where static allocation of this type
-is not possible due to its implementation being opaque at build time.
-
-
-.. c:function:: Py_tss_t* PyThread_tss_alloc()
-
- Return a value which is the same state as a value initialized with
- :c:macro:`Py_tss_NEEDS_INIT`, or ``NULL`` in the case of dynamic allocation
- failure.
-
-
-.. c:function:: void PyThread_tss_free(Py_tss_t *key)
-
- Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after
- first calling :c:func:`PyThread_tss_delete` to ensure any associated
- thread locals have been unassigned. This is a no-op if the *key*
- argument is ``NULL``.
-
- .. note::
- A freed key becomes a dangling pointer. You should reset the key to
- ``NULL``.
-
-
-Methods
-~~~~~~~
-
-The parameter *key* of these functions must not be ``NULL``. Moreover, the
-behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are
-undefined if the given :c:type:`Py_tss_t` has not been initialized by
-:c:func:`PyThread_tss_create`.
-
-
-.. c:function:: int PyThread_tss_is_created(Py_tss_t *key)
-
- Return a non-zero value if the given :c:type:`Py_tss_t` has been initialized
- by :c:func:`PyThread_tss_create`.
-
-
-.. c:function:: int PyThread_tss_create(Py_tss_t *key)
-
- Return a zero value on successful initialization of a TSS key. The behavior
- is undefined if the value pointed to by the *key* argument is not
- initialized by :c:macro:`Py_tss_NEEDS_INIT`. This function can be called
- repeatedly on the same key -- calling it on an already initialized key is a
- no-op and immediately returns success.
-
-
-.. c:function:: void PyThread_tss_delete(Py_tss_t *key)
-
- Destroy a TSS key to forget the values associated with the key across all
- threads, and change the key's initialization state to uninitialized. A
- destroyed key is able to be initialized again by
- :c:func:`PyThread_tss_create`. This function can be called repeatedly on
- the same key -- calling it on an already destroyed key is a no-op.
-
-
-.. c:function:: int PyThread_tss_set(Py_tss_t *key, void *value)
-
- Return a zero value to indicate successfully associating a :c:expr:`void*`
- value with a TSS key in the current thread. Each thread has a distinct
- mapping of the key to a :c:expr:`void*` value.
-
-
-.. c:function:: void* PyThread_tss_get(Py_tss_t *key)
-
- Return the :c:expr:`void*` value associated with a TSS key in the current
- thread. This returns ``NULL`` if no value is associated with the key in the
- current thread.
-
-
-.. _thread-local-storage-api:
-
-Thread Local Storage (TLS) API
-------------------------------
-
-.. deprecated:: 3.7
- This API is superseded by
- :ref:`Thread Specific Storage (TSS) API `.
-
-.. note::
- This version of the API does not support platforms where the native TLS key
- is defined in a way that cannot be safely cast to ``int``. On such platforms,
- :c:func:`PyThread_create_key` will return immediately with a failure status,
- and the other TLS functions will all be no-ops on such platforms.
-
-Due to the compatibility problem noted above, this version of the API should not
-be used in new code.
-
-.. c:function:: int PyThread_create_key()
-.. c:function:: void PyThread_delete_key(int key)
-.. c:function:: int PyThread_set_key_value(int key, void *value)
-.. c:function:: void* PyThread_get_key_value(int key)
-.. c:function:: void PyThread_delete_key_value(int key)
-.. c:function:: void PyThread_ReInitTLS()
-
-Synchronization Primitives
-==========================
-
-The C-API provides a basic mutual exclusion lock.
-
-.. c:type:: PyMutex
-
- A mutual exclusion lock. The :c:type:`!PyMutex` should be initialized to
- zero to represent the unlocked state. For example::
-
- PyMutex mutex = {0};
-
- Instances of :c:type:`!PyMutex` should not be copied or moved. Both the
- contents and address of a :c:type:`!PyMutex` are meaningful, and it must
- remain at a fixed, writable location in memory.
-
- .. note::
-
- A :c:type:`!PyMutex` currently occupies one byte, but the size should be
- considered unstable. The size may change in future Python releases
- without a deprecation period.
-
- .. versionadded:: 3.13
-
-.. c:function:: void PyMutex_Lock(PyMutex *m)
-
- Lock mutex *m*. If another thread has already locked it, the calling
- thread will block until the mutex is unlocked. While blocked, the thread
- will temporarily detach the :term:`thread state ` if one exists.
-
- .. versionadded:: 3.13
-
-.. c:function:: void PyMutex_Unlock(PyMutex *m)
-
- Unlock mutex *m*. The mutex must be locked --- otherwise, the function will
- issue a fatal error.
-
- .. versionadded:: 3.13
-
-.. c:function:: int PyMutex_IsLocked(PyMutex *m)
-
- Returns non-zero if the mutex *m* is currently locked, zero otherwise.
-
- .. note::
-
- This function is intended for use in assertions and debugging only and
- should not be used to make concurrency control decisions, as the lock
- state may change immediately after the check.
-
- .. versionadded:: 3.14
-
-.. _python-critical-section-api:
-
-Python Critical Section API
----------------------------
-
-The critical section API provides a deadlock avoidance layer on top of
-per-object locks for :term:`free-threaded ` CPython. They are
-intended to replace reliance on the :term:`global interpreter lock`, and are
-no-ops in versions of Python with the global interpreter lock.
-
-Critical sections are intended to be used for custom types implemented
-in C-API extensions. They should generally not be used with built-in types like
-:class:`list` and :class:`dict` because their public C-APIs
-already use critical sections internally, with the notable
-exception of :c:func:`PyDict_Next`, which requires critical section
-to be acquired externally.
-
-Critical sections avoid deadlocks by implicitly suspending active critical
-sections, hence, they do not provide exclusive access such as provided by
-traditional locks like :c:type:`PyMutex`. When a critical section is started,
-the per-object lock for the object is acquired. If the code executed inside the
-critical section calls C-API functions then it can suspend the critical section thereby
-releasing the per-object lock, so other threads can acquire the per-object lock
-for the same object.
-
-Variants that accept :c:type:`PyMutex` pointers rather than Python objects are also
-available. Use these variants to start a critical section in a situation where
-there is no :c:type:`PyObject` -- for example, when working with a C type that
-does not extend or wrap :c:type:`PyObject` but still needs to call into the C
-API in a manner that might lead to deadlocks.
-
-The functions and structs used by the macros are exposed for cases
-where C macros are not available. They should only be used as in the
-given macro expansions. Note that the sizes and contents of the structures may
-change in future Python versions.
-
-.. note::
-
- Operations that need to lock two objects at once must use
- :c:macro:`Py_BEGIN_CRITICAL_SECTION2`. You *cannot* use nested critical
- sections to lock more than one object at once, because the inner critical
- section may suspend the outer critical sections. This API does not provide
- a way to lock more than two objects at once.
-
-Example usage::
-
- static PyObject *
- set_field(MyObject *self, PyObject *value)
- {
- Py_BEGIN_CRITICAL_SECTION(self);
- Py_SETREF(self->field, Py_XNewRef(value));
- Py_END_CRITICAL_SECTION();
- Py_RETURN_NONE;
- }
-
-In the above example, :c:macro:`Py_SETREF` calls :c:macro:`Py_DECREF`, which
-can call arbitrary code through an object's deallocation function. The critical
-section API avoids potential deadlocks due to reentrancy and lock ordering
-by allowing the runtime to temporarily suspend the critical section if the
-code triggered by the finalizer blocks and calls :c:func:`PyEval_SaveThread`.
-
-.. c:macro:: Py_BEGIN_CRITICAL_SECTION(op)
-
- Acquires the per-object lock for the object *op* and begins a
- critical section.
-
- In the free-threaded build, this macro expands to::
-
- {
- PyCriticalSection _py_cs;
- PyCriticalSection_Begin(&_py_cs, (PyObject*)(op))
-
- In the default build, this macro expands to ``{``.
-
- .. versionadded:: 3.13
-
-.. c:macro:: Py_BEGIN_CRITICAL_SECTION_MUTEX(m)
-
- Locks the mutex *m* and begins a critical section.
-
- In the free-threaded build, this macro expands to::
-
- {
- PyCriticalSection _py_cs;
- PyCriticalSection_BeginMutex(&_py_cs, m)
-
- Note that unlike :c:macro:`Py_BEGIN_CRITICAL_SECTION`, there is no cast for
- the argument of the macro - it must be a :c:type:`PyMutex` pointer.
-
- On the default build, this macro expands to ``{``.
-
- .. versionadded:: 3.14
-
-.. c:macro:: Py_END_CRITICAL_SECTION()
-
- Ends the critical section and releases the per-object lock.
-
- In the free-threaded build, this macro expands to::
-
- PyCriticalSection_End(&_py_cs);
- }
-
- In the default build, this macro expands to ``}``.
-
- .. versionadded:: 3.13
-
-.. c:macro:: Py_BEGIN_CRITICAL_SECTION2(a, b)
-
- Acquires the per-objects locks for the objects *a* and *b* and begins a
- critical section. The locks are acquired in a consistent order (lowest
- address first) to avoid lock ordering deadlocks.
-
- In the free-threaded build, this macro expands to::
-
- {
- PyCriticalSection2 _py_cs2;
- PyCriticalSection2_Begin(&_py_cs2, (PyObject*)(a), (PyObject*)(b))
-
- In the default build, this macro expands to ``{``.
-
- .. versionadded:: 3.13
-
-.. c:macro:: Py_BEGIN_CRITICAL_SECTION2_MUTEX(m1, m2)
-
- Locks the mutexes *m1* and *m2* and begins a critical section.
-
- In the free-threaded build, this macro expands to::
-
- {
- PyCriticalSection2 _py_cs2;
- PyCriticalSection2_BeginMutex(&_py_cs2, m1, m2)
-
- Note that unlike :c:macro:`Py_BEGIN_CRITICAL_SECTION2`, there is no cast for
- the arguments of the macro - they must be :c:type:`PyMutex` pointers.
-
- On the default build, this macro expands to ``{``.
-
- .. versionadded:: 3.14
-
-.. c:macro:: Py_END_CRITICAL_SECTION2()
-
- Ends the critical section and releases the per-object locks.
-
- In the free-threaded build, this macro expands to::
-
- PyCriticalSection2_End(&_py_cs2);
- }
-
- In the default build, this macro expands to ``}``.
-
- .. versionadded:: 3.13
-
-
-Legacy Locking APIs
--------------------
-
-These APIs are obsolete since Python 3.13 with the introduction of
-:c:type:`PyMutex`.
-
-.. versionchanged:: 3.15
- These APIs are now a simple wrapper around ``PyMutex``.
-
-
-.. c:type:: PyThread_type_lock
-
- A pointer to a mutual exclusion lock.
-
-
-.. c:type:: PyLockStatus
-
- The result of acquiring a lock with a timeout.
-
- .. c:namespace:: NULL
-
- .. c:enumerator:: PY_LOCK_FAILURE
-
- Failed to acquire the lock.
-
- .. c:enumerator:: PY_LOCK_ACQUIRED
-
- The lock was successfully acquired.
-
- .. c:enumerator:: PY_LOCK_INTR
-
- The lock was interrupted by a signal.
-
-
-.. c:function:: PyThread_type_lock PyThread_allocate_lock(void)
-
- Allocate a new lock.
-
- On success, this function returns a lock; on failure, this
- function returns ``0`` without an exception set.
-
- The caller does not need to hold an :term:`attached thread state`.
-
- .. versionchanged:: 3.15
- This function now always uses :c:type:`PyMutex`. In prior versions, this
- would use a lock provided by the operating system.
-
-
-.. c:function:: void PyThread_free_lock(PyThread_type_lock lock)
-
- Destroy *lock*. The lock should not be held by any thread when calling
- this.
-
- The caller does not need to hold an :term:`attached thread state`.
-
-
-.. c:function:: PyLockStatus PyThread_acquire_lock_timed(PyThread_type_lock lock, long long microseconds, int intr_flag)
-
- Acquire *lock* with a timeout.
-
- This will wait for *microseconds* microseconds to acquire the lock. If the
- timeout expires, this function returns :c:enumerator:`PY_LOCK_FAILURE`.
- If *microseconds* is ``-1``, this will wait indefinitely until the lock has
- been released.
-
- If *intr_flag* is ``1``, acquiring the lock may be interrupted by a signal,
- in which case this function returns :c:enumerator:`PY_LOCK_INTR`. Upon
- interruption, it's generally expected that the caller makes a call to
- :c:func:`Py_MakePendingCalls` to propagate an exception to Python code.
-
- If the lock is successfully acquired, this function returns
- :c:enumerator:`PY_LOCK_ACQUIRED`.
-
- The caller does not need to hold an :term:`attached thread state`.
-
-
-.. c:function:: int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
-
- Acquire *lock*.
-
- If *waitflag* is ``1`` and another thread currently holds the lock, this
- function will wait until the lock can be acquired and will always return
- ``1``.
-
- If *waitflag* is ``0`` and another thread holds the lock, this function will
- not wait and instead return ``0``. If the lock is not held by any other
- thread, then this function will acquire it and return ``1``.
-
- Unlike :c:func:`PyThread_acquire_lock_timed`, acquiring the lock cannot be
- interrupted by a signal.
-
- The caller does not need to hold an :term:`attached thread state`.
-
-
-.. c:function:: int PyThread_release_lock(PyThread_type_lock lock)
-
- Release *lock*. If *lock* is not held, then this function issues a
- fatal error.
-
- The caller does not need to hold an :term:`attached thread state`.
-
-
-Operating System Thread APIs
-============================
-
-.. c:macro:: PYTHREAD_INVALID_THREAD_ID
-
- Sentinel value for an invalid thread ID.
-
- This is currently equivalent to ``(unsigned long)-1``.
-
-
-.. c:function:: unsigned long PyThread_start_new_thread(void (*func)(void *), void *arg)
-
- Start function *func* in a new thread with argument *arg*.
- The resulting thread is not intended to be joined.
-
- *func* must not be ``NULL``, but *arg* may be ``NULL``.
-
- On success, this function returns the identifier of the new thread; on failure,
- this returns :c:macro:`PYTHREAD_INVALID_THREAD_ID`.
-
- The caller does not need to hold an :term:`attached thread state`.
-
-
-.. c:function:: unsigned long PyThread_get_thread_ident(void)
-
- Return the identifier of the current thread, which will never be zero.
-
- This function cannot fail, and the caller does not need to hold an
- :term:`attached thread state`.
-
- .. seealso::
- :py:func:`threading.get_ident`
-
-
-.. c:function:: PyObject *PyThread_GetInfo(void)
-
- Get general information about the current thread in the form of a
- :ref:`struct sequence ` object. This information is
- accessible as :py:attr:`sys.thread_info` in Python.
-
- On success, this returns a new :term:`strong reference` to the thread
- information; on failure, this returns ``NULL`` with an exception set.
-
- The caller must hold an :term:`attached thread state`.
-
-
-.. c:macro:: PY_HAVE_THREAD_NATIVE_ID
-
- This macro is defined when the system supports native thread IDs.
-
-
-.. c:function:: unsigned long PyThread_get_thread_native_id(void)
-
- Get the native identifier of the current thread as it was assigned by the operating
- system's kernel, which will never be less than zero.
-
- This function is only available when :c:macro:`PY_HAVE_THREAD_NATIVE_ID` is
- defined.
-
- This function cannot fail, and the caller does not need to hold an
- :term:`attached thread state`.
-
- .. seealso::
- :py:func:`threading.get_native_id`
-
-
-.. c:function:: void PyThread_exit_thread(void)
-
- Terminate the current thread. This function is generally considered unsafe
- and should be avoided. It is kept solely for backwards compatibility.
-
- This function is only safe to call if all functions in the full call
- stack are written to safely allow it.
-
- .. warning::
-
- If the current system uses POSIX threads (also known as "pthreads"),
- this calls :manpage:`pthread_exit(3)`, which attempts to unwind the stack
- and call C++ destructors on some libc implementations. However, if a
- ``noexcept`` function is reached, it may terminate the process.
- Other systems, such as macOS, do unwinding.
-
- On Windows, this function calls ``_endthreadex()``, which kills the thread
- without calling C++ destructors.
-
- In any case, there is a risk of corruption on the thread's stack.
-
- .. deprecated:: 3.14
-
-
-.. c:function:: void PyThread_init_thread(void)
-
- Initialize ``PyThread*`` APIs. Python executes this function automatically,
- so there's little need to call it from an extension module.
-
-
-.. c:function:: int PyThread_set_stacksize(size_t size)
-
- Set the stack size of the current thread to *size* bytes.
-
- This function returns ``0`` on success, ``-1`` if *size* is invalid, or
- ``-2`` if the system does not support changing the stack size. This function
- does not set exceptions.
-
- The caller does not need to hold an :term:`attached thread state`.
-
-
-.. c:function:: size_t PyThread_get_stacksize(void)
-
- Return the stack size of the current thread in bytes, or ``0`` if the system's
- default stack size is in use.
-
- The caller does not need to hold an :term:`attached thread state`.
+- :ref:`initialization`
+- :ref:`threads`
+- :ref:`synchronization`
+- :ref:`thread-local-storage`
+- :ref:`sub-interpreter-support`
+- :ref:`profiling`
diff --git a/Doc/c-api/init_config.rst b/Doc/c-api/init_config.rst
index c345029e4acd49..f6dc604a609cb1 100644
--- a/Doc/c-api/init_config.rst
+++ b/Doc/c-api/init_config.rst
@@ -544,9 +544,9 @@ Configuration Options
Visibility:
-* Public: Can by get by :c:func:`PyConfig_Get` and set by
+* Public: Can be retrieved by :c:func:`PyConfig_Get` and set by
:c:func:`PyConfig_Set`.
-* Read-only: Can by get by :c:func:`PyConfig_Get`, but cannot be set by
+* Read-only: Can be retrieved by :c:func:`PyConfig_Get`, but cannot be set by
:c:func:`PyConfig_Set`.
@@ -1153,7 +1153,7 @@ PyConfig
Most ``PyConfig`` methods :ref:`preinitialize Python ` if needed.
In that case, the Python preinitialization configuration
- (:c:type:`PyPreConfig`) in based on the :c:type:`PyConfig`. If configuration
+ (:c:type:`PyPreConfig`) is based on the :c:type:`PyConfig`. If configuration
fields which are in common with :c:type:`PyPreConfig` are tuned, they must
be set before calling a :c:type:`PyConfig` method:
@@ -2299,13 +2299,91 @@ Py_GetArgcArgv()
See also :c:member:`PyConfig.orig_argv` member.
-Delaying main module execution
-==============================
-In some embedding use cases, it may be desirable to separate interpreter initialization
-from the execution of the main module.
+Multi-Phase Initialization Private Provisional API
+==================================================
-This separation can be achieved by setting ``PyConfig.run_command`` to the empty
-string during initialization (to prevent the interpreter from dropping into the
-interactive prompt), and then subsequently executing the desired main module
-code using ``__main__.__dict__`` as the global namespace.
+This section is a private provisional API introducing multi-phase
+initialization, the core feature of :pep:`432`:
+
+* "Core" initialization phase, "bare minimum Python":
+
+ * Builtin types;
+ * Builtin exceptions;
+ * Builtin and frozen modules;
+ * The :mod:`sys` module is only partially initialized
+ (ex: :data:`sys.path` doesn't exist yet).
+
+* "Main" initialization phase, Python is fully initialized:
+
+ * Install and configure :mod:`importlib`;
+ * Apply the :ref:`Path Configuration `;
+ * Install signal handlers;
+ * Finish :mod:`sys` module initialization (ex: create :data:`sys.stdout`
+ and :data:`sys.path`);
+ * Enable optional features like :mod:`faulthandler` and :mod:`tracemalloc`;
+ * Import the :mod:`site` module;
+ * etc.
+
+Private provisional API:
+
+.. c:member:: int PyConfig._init_main
+
+ If set to ``0``, :c:func:`Py_InitializeFromConfig` stops at the "Core"
+ initialization phase.
+
+.. c:function:: PyStatus _Py_InitializeMain(void)
+
+ Move to the "Main" initialization phase, finish the Python initialization.
+
+No module is imported during the "Core" phase and the ``importlib`` module is
+not configured: the :ref:`Path Configuration ` is only
+applied during the "Main" phase. It may allow to customize Python in Python to
+override or tune the :ref:`Path Configuration `, maybe
+install a custom :data:`sys.meta_path` importer or an import hook, etc.
+
+It may become possible to calculate the :ref:`Path Configuration
+` in Python, after the Core phase and before the Main phase,
+which is one of the :pep:`432` motivation.
+
+The "Core" phase is not properly defined: what should be and what should
+not be available at this phase is not specified yet. The API is marked
+as private and provisional: the API can be modified or even be removed
+anytime until a proper public API is designed.
+
+Example running Python code between "Core" and "Main" initialization
+phases::
+
+ void init_python(void)
+ {
+ PyStatus status;
+
+ PyConfig config;
+ PyConfig_InitPythonConfig(&config);
+ config._init_main = 0;
+
+ /* ... customize 'config' configuration ... */
+
+ status = Py_InitializeFromConfig(&config);
+ PyConfig_Clear(&config);
+ if (PyStatus_Exception(status)) {
+ Py_ExitStatusException(status);
+ }
+
+ /* Use sys.stderr because sys.stdout is only created
+ by _Py_InitializeMain() */
+ int res = PyRun_SimpleString(
+ "import sys; "
+ "print('Run Python code before _Py_InitializeMain', "
+ "file=sys.stderr)");
+ if (res < 0) {
+ exit(1);
+ }
+
+ /* ... put more configuration code here ... */
+
+ status = _Py_InitializeMain();
+ if (PyStatus_Exception(status)) {
+ Py_ExitStatusException(status);
+ }
+ }
diff --git a/Doc/c-api/interp-lifecycle.rst b/Doc/c-api/interp-lifecycle.rst
new file mode 100644
index 00000000000000..189d8e424f6814
--- /dev/null
+++ b/Doc/c-api/interp-lifecycle.rst
@@ -0,0 +1,797 @@
+.. highlight:: c
+
+.. _initialization:
+
+Interpreter initialization and finalization
+===========================================
+
+See :ref:`Python Initialization Configuration ` for details
+on how to configure the interpreter prior to initialization.
+
+.. _pre-init-safe:
+
+Before Python initialization
+----------------------------
+
+In an application embedding Python, the :c:func:`Py_Initialize` function must
+be called before using any other Python/C API functions; with the exception of
+a few functions and the :ref:`global configuration variables
+`.
+
+The following functions can be safely called before Python is initialized:
+
+* Functions that initialize the interpreter:
+
+ * :c:func:`Py_Initialize`
+ * :c:func:`Py_InitializeEx`
+ * :c:func:`Py_InitializeFromConfig`
+ * :c:func:`Py_BytesMain`
+ * :c:func:`Py_Main`
+ * the runtime pre-initialization functions covered in :ref:`init-config`
+
+* Configuration functions:
+
+ * :c:func:`PyImport_AppendInittab`
+ * :c:func:`PyImport_ExtendInittab`
+ * :c:func:`!PyInitFrozenExtensions`
+ * :c:func:`PyMem_SetAllocator`
+ * :c:func:`PyMem_SetupDebugHooks`
+ * :c:func:`PyObject_SetArenaAllocator`
+ * :c:func:`Py_SetProgramName`
+ * :c:func:`Py_SetPythonHome`
+ * the configuration functions covered in :ref:`init-config`
+
+* Informative functions:
+
+ * :c:func:`Py_IsInitialized`
+ * :c:func:`PyMem_GetAllocator`
+ * :c:func:`PyObject_GetArenaAllocator`
+ * :c:func:`Py_GetBuildInfo`
+ * :c:func:`Py_GetCompiler`
+ * :c:func:`Py_GetCopyright`
+ * :c:func:`Py_GetPlatform`
+ * :c:func:`Py_GetVersion`
+ * :c:func:`Py_IsInitialized`
+
+* Utilities:
+
+ * :c:func:`Py_DecodeLocale`
+ * the status reporting and utility functions covered in :ref:`init-config`
+
+* Memory allocators:
+
+ * :c:func:`PyMem_RawMalloc`
+ * :c:func:`PyMem_RawRealloc`
+ * :c:func:`PyMem_RawCalloc`
+ * :c:func:`PyMem_RawFree`
+
+* Synchronization:
+
+ * :c:func:`PyMutex_Lock`
+ * :c:func:`PyMutex_Unlock`
+
+.. note::
+
+ Despite their apparent similarity to some of the functions listed above,
+ the following functions **should not be called** before the interpreter has
+ been initialized: :c:func:`Py_EncodeLocale`, :c:func:`PyEval_InitThreads`, and
+ :c:func:`Py_RunMain`.
+
+
+.. _global-conf-vars:
+
+Global configuration variables
+------------------------------
+
+Python has variables for the global configuration to control different features
+and options. By default, these flags are controlled by :ref:`command line
+options `.
+
+When a flag is set by an option, the value of the flag is the number of times
+that the option was set. For example, ``-b`` sets :c:data:`Py_BytesWarningFlag`
+to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2.
+
+
+.. c:var:: int Py_BytesWarningFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.bytes_warning` should be used instead, see :ref:`Python
+ Initialization Configuration `.
+
+ Issue a warning when comparing :class:`bytes` or :class:`bytearray` with
+ :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater
+ or equal to ``2``.
+
+ Set by the :option:`-b` option.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_DebugFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.parser_debug` should be used instead, see :ref:`Python
+ Initialization Configuration `.
+
+ Turn on parser debugging output (for expert only, depending on compilation
+ options).
+
+ Set by the :option:`-d` option and the :envvar:`PYTHONDEBUG` environment
+ variable.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_DontWriteBytecodeFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.write_bytecode` should be used instead, see :ref:`Python
+ Initialization Configuration `.
+
+ If set to non-zero, Python won't try to write ``.pyc`` files on the
+ import of source modules.
+
+ Set by the :option:`-B` option and the :envvar:`PYTHONDONTWRITEBYTECODE`
+ environment variable.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_FrozenFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.pathconfig_warnings` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ Private flag used by ``_freeze_module`` and ``frozenmain`` programs.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_HashRandomizationFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.hash_seed` and :c:member:`PyConfig.use_hash_seed` should
+ be used instead, see :ref:`Python Initialization Configuration
+ `.
+
+ Set to ``1`` if the :envvar:`PYTHONHASHSEED` environment variable is set to
+ a non-empty string.
+
+ If the flag is non-zero, read the :envvar:`PYTHONHASHSEED` environment
+ variable to initialize the secret hash seed.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_IgnoreEnvironmentFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.use_environment` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ Ignore all :envvar:`!PYTHON*` environment variables, e.g.
+ :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
+
+ Set by the :option:`-E` and :option:`-I` options.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_InspectFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.inspect` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ When a script is passed as first argument or the :option:`-c` option is used,
+ enter interactive mode after executing the script or the command, even when
+ :data:`sys.stdin` does not appear to be a terminal.
+
+ Set by the :option:`-i` option and the :envvar:`PYTHONINSPECT` environment
+ variable.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_InteractiveFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.interactive` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ Set by the :option:`-i` option.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_IsolatedFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.isolated` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ Run Python in isolated mode. In isolated mode :data:`sys.path` contains
+ neither the script's directory nor the user's site-packages directory.
+
+ Set by the :option:`-I` option.
+
+ .. versionadded:: 3.4
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_LegacyWindowsFSEncodingFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyPreConfig.legacy_windows_fs_encoding` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ If the flag is non-zero, use the ``mbcs`` encoding with ``replace`` error
+ handler, instead of the UTF-8 encoding with ``surrogatepass`` error handler,
+ for the :term:`filesystem encoding and error handler`.
+
+ Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment
+ variable is set to a non-empty string.
+
+ See :pep:`529` for more details.
+
+ .. availability:: Windows.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_LegacyWindowsStdioFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.legacy_windows_stdio` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ If the flag is non-zero, use :class:`io.FileIO` instead of
+ :class:`!io._WindowsConsoleIO` for :mod:`sys` standard streams.
+
+ Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment
+ variable is set to a non-empty string.
+
+ See :pep:`528` for more details.
+
+ .. availability:: Windows.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_NoSiteFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.site_import` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ Disable the import of the module :mod:`site` and the site-dependent
+ manipulations of :data:`sys.path` that it entails. Also disable these
+ manipulations if :mod:`site` is explicitly imported later (call
+ :func:`site.main` if you want them to be triggered).
+
+ Set by the :option:`-S` option.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_NoUserSiteDirectory
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.user_site_directory` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ Don't add the :data:`user site-packages directory ` to
+ :data:`sys.path`.
+
+ Set by the :option:`-s` and :option:`-I` options, and the
+ :envvar:`PYTHONNOUSERSITE` environment variable.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_OptimizeFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.optimization_level` should be used instead, see
+ :ref:`Python Initialization Configuration `.
+
+ Set by the :option:`-O` option and the :envvar:`PYTHONOPTIMIZE` environment
+ variable.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_QuietFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.quiet` should be used instead, see :ref:`Python
+ Initialization Configuration `.
+
+ Don't display the copyright and version messages even in interactive mode.
+
+ Set by the :option:`-q` option.
+
+ .. versionadded:: 3.2
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_UnbufferedStdioFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.buffered_stdio` should be used instead, see :ref:`Python
+ Initialization Configuration `.
+
+ Force the stdout and stderr streams to be unbuffered.
+
+ Set by the :option:`-u` option and the :envvar:`PYTHONUNBUFFERED`
+ environment variable.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+.. c:var:: int Py_VerboseFlag
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.verbose` should be used instead, see :ref:`Python
+ Initialization Configuration `.
+
+ Print a message each time a module is initialized, showing the place
+ (filename or built-in module) from which it is loaded. If greater or equal
+ to ``2``, print a message for each file that is checked for when
+ searching for a module. Also provides information on module cleanup at exit.
+
+ Set by the :option:`-v` option and the :envvar:`PYTHONVERBOSE` environment
+ variable.
+
+ .. deprecated-removed:: 3.12 3.15
+
+
+Initializing and finalizing the interpreter
+-------------------------------------------
+
+.. c:function:: void Py_Initialize()
+
+ .. index::
+ single: PyEval_InitThreads()
+ single: modules (in module sys)
+ single: path (in module sys)
+ pair: module; builtins
+ pair: module; __main__
+ pair: module; sys
+ triple: module; search; path
+ single: Py_FinalizeEx (C function)
+
+ Initialize the Python interpreter. In an application embedding Python,
+ this should be called before using any other Python/C API functions; see
+ :ref:`Before Python Initialization ` for the few exceptions.
+
+ This initializes the table of loaded modules (``sys.modules``), and creates
+ the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`.
+ It also initializes the module search path (``sys.path``). It does not set
+ ``sys.argv``; use the :ref:`Python Initialization Configuration `
+ API for that. This is a no-op when called for a second time (without calling
+ :c:func:`Py_FinalizeEx` first). There is no return value; it is a fatal
+ error if the initialization fails.
+
+ Use :c:func:`Py_InitializeFromConfig` to customize the
+ :ref:`Python Initialization Configuration `.
+
+ .. note::
+ On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``,
+ which will also affect non-Python uses of the console using the C Runtime.
+
+
+.. c:function:: void Py_InitializeEx(int initsigs)
+
+ This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If
+ *initsigs* is ``0``, it skips initialization registration of signal handlers,
+ which may be useful when CPython is embedded as part of a larger application.
+
+ Use :c:func:`Py_InitializeFromConfig` to customize the
+ :ref:`Python Initialization Configuration `.
+
+
+.. c:function:: PyStatus Py_InitializeFromConfig(const PyConfig *config)
+
+ Initialize Python from *config* configuration, as described in
+ :ref:`init-from-config`.
+
+ See the :ref:`init-config` section for details on pre-initializing the
+ interpreter, populating the runtime configuration structure, and querying
+ the returned status structure.
+
+
+.. c:function:: int Py_IsInitialized()
+
+ Return true (nonzero) when the Python interpreter has been initialized, false
+ (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until
+ :c:func:`Py_Initialize` is called again.
+
+
+.. c:function:: int Py_IsFinalizing()
+
+ Return true (non-zero) if the main Python interpreter is
+ :term:`shutting down `. Return false (zero) otherwise.
+
+ .. versionadded:: 3.13
+
+
+.. c:function:: int Py_FinalizeEx()
+
+ Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of
+ Python/C API functions, and destroy all sub-interpreters (see
+ :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since
+ the last call to :c:func:`Py_Initialize`. This is a no-op when called for a second
+ time (without calling :c:func:`Py_Initialize` again first).
+
+ Since this is the reverse of :c:func:`Py_Initialize`, it should be called
+ in the same thread with the same interpreter active. That means
+ the main thread and the main interpreter.
+ This should never be called while :c:func:`Py_RunMain` is running.
+
+ Normally the return value is ``0``.
+ If there were errors during finalization (flushing buffered data),
+ ``-1`` is returned.
+
+ Note that Python will do a best effort at freeing all memory allocated by the Python
+ interpreter. Therefore, any C-Extension should make sure to correctly clean up all
+ of the previously allocated PyObjects before using them in subsequent calls to
+ :c:func:`Py_Initialize`. Otherwise it could introduce vulnerabilities and incorrect
+ behavior.
+
+ This function is provided for a number of reasons. An embedding application
+ might want to restart Python without having to restart the application itself.
+ An application that has loaded the Python interpreter from a dynamically
+ loadable library (or DLL) might want to free all memory allocated by Python
+ before unloading the DLL. During a hunt for memory leaks in an application a
+ developer might want to free all memory allocated by Python before exiting from
+ the application.
+
+ **Bugs and caveats:** The destruction of modules and objects in modules is done
+ in random order; this may cause destructors (:meth:`~object.__del__` methods) to fail
+ when they depend on other objects (even functions) or modules. Dynamically
+ loaded extension modules loaded by Python are not unloaded. Small amounts of
+ memory allocated by the Python interpreter may not be freed (if you find a leak,
+ please report it). Memory tied up in circular references between objects is not
+ freed. Interned strings will all be deallocated regardless of their reference count.
+ Some memory allocated by extension modules may not be freed. Some extensions may not
+ work properly if their initialization routine is called more than once; this can
+ happen if an application calls :c:func:`Py_Initialize` and :c:func:`Py_FinalizeEx`
+ more than once. :c:func:`Py_FinalizeEx` must not be called recursively from
+ within itself. Therefore, it must not be called by any code that may be run
+ as part of the interpreter shutdown process, such as :py:mod:`atexit`
+ handlers, object finalizers, or any code that may be run while flushing the
+ stdout and stderr files.
+
+ .. audit-event:: cpython._PySys_ClearAuditHooks "" c.Py_FinalizeEx
+
+ .. versionadded:: 3.6
+
+
+.. c:function:: void Py_Finalize()
+
+ This is a backwards-compatible version of :c:func:`Py_FinalizeEx` that
+ disregards the return value.
+
+
+.. c:function:: int Py_BytesMain(int argc, char **argv)
+
+ Similar to :c:func:`Py_Main` but *argv* is an array of bytes strings,
+ allowing the calling application to delegate the text decoding step to
+ the CPython runtime.
+
+ .. versionadded:: 3.8
+
+
+.. c:function:: int Py_Main(int argc, wchar_t **argv)
+
+ The main program for the standard interpreter, encapsulating a full
+ initialization/finalization cycle, as well as additional
+ behaviour to implement reading configurations settings from the environment
+ and command line, and then executing ``__main__`` in accordance with
+ :ref:`using-on-cmdline`.
+
+ This is made available for programs which wish to support the full CPython
+ command line interface, rather than just embedding a Python runtime in a
+ larger application.
+
+ The *argc* and *argv* parameters are similar to those which are passed to a
+ C program's :c:func:`main` function, except that the *argv* entries are first
+ converted to ``wchar_t`` using :c:func:`Py_DecodeLocale`. It is also
+ important to note that the argument list entries may be modified to point to
+ strings other than those passed in (however, the contents of the strings
+ pointed to by the argument list are not modified).
+
+ The return value is ``2`` if the argument list does not represent a valid
+ Python command line, and otherwise the same as :c:func:`Py_RunMain`.
+
+ In terms of the CPython runtime configuration APIs documented in the
+ :ref:`runtime configuration ` section (and without accounting
+ for error handling), ``Py_Main`` is approximately equivalent to::
+
+ PyConfig config;
+ PyConfig_InitPythonConfig(&config);
+ PyConfig_SetArgv(&config, argc, argv);
+ Py_InitializeFromConfig(&config);
+ PyConfig_Clear(&config);
+
+ Py_RunMain();
+
+ In normal usage, an embedding application will call this function
+ *instead* of calling :c:func:`Py_Initialize`, :c:func:`Py_InitializeEx` or
+ :c:func:`Py_InitializeFromConfig` directly, and all settings will be applied
+ as described elsewhere in this documentation. If this function is instead
+ called *after* a preceding runtime initialization API call, then exactly
+ which environmental and command line configuration settings will be updated
+ is version dependent (as it depends on which settings correctly support
+ being modified after they have already been set once when the runtime was
+ first initialized).
+
+
+.. c:function:: int Py_RunMain(void)
+
+ Executes the main module in a fully configured CPython runtime.
+
+ Executes the command (:c:member:`PyConfig.run_command`), the script
+ (:c:member:`PyConfig.run_filename`) or the module
+ (:c:member:`PyConfig.run_module`) specified on the command line or in the
+ configuration. If none of these values are set, runs the interactive Python
+ prompt (REPL) using the ``__main__`` module's global namespace.
+
+ If :c:member:`PyConfig.inspect` is not set (the default), the return value
+ will be ``0`` if the interpreter exits normally (that is, without raising
+ an exception), the exit status of an unhandled :exc:`SystemExit`, or ``1``
+ for any other unhandled exception.
+
+ If :c:member:`PyConfig.inspect` is set (such as when the :option:`-i` option
+ is used), rather than returning when the interpreter exits, execution will
+ instead resume in an interactive Python prompt (REPL) using the ``__main__``
+ module's global namespace. If the interpreter exited with an exception, it
+ is immediately raised in the REPL session. The function return value is
+ then determined by the way the *REPL session* terminates: ``0``, ``1``, or
+ the status of a :exc:`SystemExit`, as specified above.
+
+ This function always finalizes the Python interpreter before it returns.
+
+ See :ref:`Python Configuration ` for an example of a
+ customized Python that always runs in isolated mode using
+ :c:func:`Py_RunMain`.
+
+.. c:function:: int PyUnstable_AtExit(PyInterpreterState *interp, void (*func)(void *), void *data)
+
+ Register an :mod:`atexit` callback for the target interpreter *interp*.
+ This is similar to :c:func:`Py_AtExit`, but takes an explicit interpreter and
+ data pointer for the callback.
+
+ There must be an :term:`attached thread state` for *interp*.
+
+ .. versionadded:: 3.13
+
+
+.. _cautions-regarding-runtime-finalization:
+
+Cautions regarding runtime finalization
+---------------------------------------
+
+In the late stage of :term:`interpreter shutdown`, after attempting to wait for
+non-daemon threads to exit (though this can be interrupted by
+:class:`KeyboardInterrupt`) and running the :mod:`atexit` functions, the runtime
+is marked as *finalizing*: :c:func:`Py_IsFinalizing` and
+:func:`sys.is_finalizing` return true. At this point, only the *finalization
+thread* that initiated finalization (typically the main thread) is allowed to
+acquire the :term:`GIL`.
+
+If any thread, other than the finalization thread, attempts to attach a :term:`thread state`
+during finalization, either explicitly or
+implicitly, the thread enters **a permanently blocked state**
+where it remains until the program exits. In most cases this is harmless, but this can result
+in deadlock if a later stage of finalization attempts to acquire a lock owned by the
+blocked thread, or otherwise waits on the blocked thread.
+
+Gross? Yes. This prevents random crashes and/or unexpectedly skipped C++
+finalizations further up the call stack when such threads were forcibly exited
+here in CPython 3.13 and earlier. The CPython runtime :term:`thread state` C APIs
+have never had any error reporting or handling expectations at :term:`thread state`
+attachment time that would've allowed for graceful exit from this situation. Changing that
+would require new stable C APIs and rewriting the majority of C code in the
+CPython ecosystem to use those with error handling.
+
+
+Process-wide parameters
+-----------------------
+
+.. c:function:: void Py_SetProgramName(const wchar_t *name)
+
+ .. index::
+ single: Py_Initialize()
+ single: main()
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.program_name` should be used instead, see :ref:`Python
+ Initialization Configuration `.
+
+ This function should be called before :c:func:`Py_Initialize` is called for
+ the first time, if it is called at all. It tells the interpreter the value
+ of the ``argv[0]`` argument to the :c:func:`main` function of the program
+ (converted to wide characters).
+ This is used by some other functions below to find
+ the Python run-time libraries relative to the interpreter executable. The
+ default value is ``'python'``. The argument should point to a
+ zero-terminated wide character string in static storage whose contents will not
+ change for the duration of the program's execution. No code in the Python
+ interpreter will change the contents of this storage.
+
+ Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
+ :c:expr:`wchar_t*` string.
+
+ .. deprecated-removed:: 3.11 3.15
+
+
+.. c:function:: const char* Py_GetVersion()
+
+ Return the version of this Python interpreter. This is a string that looks
+ something like ::
+
+ "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
+
+ .. index:: single: version (in module sys)
+
+ The first word (up to the first space character) is the current Python version;
+ the first characters are the major and minor version separated by a
+ period. The returned string points into static storage; the caller should not
+ modify its value. The value is available to Python code as :data:`sys.version`.
+
+ See also the :c:var:`Py_Version` constant.
+
+
+.. c:function:: const char* Py_GetPlatform()
+
+ .. index:: single: platform (in module sys)
+
+ Return the platform identifier for the current platform. On Unix, this is
+ formed from the "official" name of the operating system, converted to lower
+ case, followed by the major revision number; e.g., for Solaris 2.x, which is
+ also known as SunOS 5.x, the value is ``'sunos5'``. On macOS, it is
+ ``'darwin'``. On Windows, it is ``'win'``. The returned string points into
+ static storage; the caller should not modify its value. The value is available
+ to Python code as ``sys.platform``.
+
+
+.. c:function:: const char* Py_GetCopyright()
+
+ Return the official copyright string for the current Python version, for example
+
+ ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``
+
+ .. index:: single: copyright (in module sys)
+
+ The returned string points into static storage; the caller should not modify its
+ value. The value is available to Python code as ``sys.copyright``.
+
+
+.. c:function:: const char* Py_GetCompiler()
+
+ Return an indication of the compiler used to build the current Python version,
+ in square brackets, for example::
+
+ "[GCC 2.7.2.2]"
+
+ .. index:: single: version (in module sys)
+
+ The returned string points into static storage; the caller should not modify its
+ value. The value is available to Python code as part of the variable
+ ``sys.version``.
+
+
+.. c:function:: const char* Py_GetBuildInfo()
+
+ Return information about the sequence number and build date and time of the
+ current Python interpreter instance, for example ::
+
+ "#67, Aug 1 1997, 22:34:28"
+
+ .. index:: single: version (in module sys)
+
+ The returned string points into static storage; the caller should not modify its
+ value. The value is available to Python code as part of the variable
+ ``sys.version``.
+
+
+.. c:function:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
+
+ .. index::
+ single: main()
+ single: Py_FatalError()
+ single: argv (in module sys)
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.argv`, :c:member:`PyConfig.parse_argv` and
+ :c:member:`PyConfig.safe_path` should be used instead, see :ref:`Python
+ Initialization Configuration `.
+
+ Set :data:`sys.argv` based on *argc* and *argv*. These parameters are
+ similar to those passed to the program's :c:func:`main` function with the
+ difference that the first entry should refer to the script file to be
+ executed rather than the executable hosting the Python interpreter. If there
+ isn't a script that will be run, the first entry in *argv* can be an empty
+ string. If this function fails to initialize :data:`sys.argv`, a fatal
+ condition is signalled using :c:func:`Py_FatalError`.
+
+ If *updatepath* is zero, this is all the function does. If *updatepath*
+ is non-zero, the function also modifies :data:`sys.path` according to the
+ following algorithm:
+
+ - If the name of an existing script is passed in ``argv[0]``, the absolute
+ path of the directory where the script is located is prepended to
+ :data:`sys.path`.
+ - Otherwise (that is, if *argc* is ``0`` or ``argv[0]`` doesn't point
+ to an existing file name), an empty string is prepended to
+ :data:`sys.path`, which is the same as prepending the current working
+ directory (``"."``).
+
+ Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
+ :c:expr:`wchar_t*` string.
+
+ See also :c:member:`PyConfig.orig_argv` and :c:member:`PyConfig.argv`
+ members of the :ref:`Python Initialization Configuration `.
+
+ .. note::
+ It is recommended that applications embedding the Python interpreter
+ for purposes other than executing a single script pass ``0`` as *updatepath*,
+ and update :data:`sys.path` themselves if desired.
+ See :cve:`2008-5983`.
+
+ On versions before 3.1.3, you can achieve the same effect by manually
+ popping the first :data:`sys.path` element after having called
+ :c:func:`PySys_SetArgv`, for example using::
+
+ PyRun_SimpleString("import sys; sys.path.pop(0)\n");
+
+ .. versionadded:: 3.1.3
+
+ .. deprecated-removed:: 3.11 3.15
+
+
+.. c:function:: void PySys_SetArgv(int argc, wchar_t **argv)
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.argv` and :c:member:`PyConfig.parse_argv` should be used
+ instead, see :ref:`Python Initialization Configuration `.
+
+ This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set
+ to ``1`` unless the :program:`python` interpreter was started with the
+ :option:`-I`.
+
+ Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
+ :c:expr:`wchar_t*` string.
+
+ See also :c:member:`PyConfig.orig_argv` and :c:member:`PyConfig.argv`
+ members of the :ref:`Python Initialization Configuration `.
+
+ .. versionchanged:: 3.4 The *updatepath* value depends on :option:`-I`.
+
+ .. deprecated-removed:: 3.11 3.15
+
+
+.. c:function:: void Py_SetPythonHome(const wchar_t *home)
+
+ This API is kept for backward compatibility: setting
+ :c:member:`PyConfig.home` should be used instead, see :ref:`Python
+ Initialization Configuration `.
+
+ Set the default "home" directory, that is, the location of the standard
+ Python libraries. See :envvar:`PYTHONHOME` for the meaning of the
+ argument string.
+
+ The argument should point to a zero-terminated character string in static
+ storage whose contents will not change for the duration of the program's
+ execution. No code in the Python interpreter will change the contents of
+ this storage.
+
+ Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
+ :c:expr:`wchar_t*` string.
+
+ .. deprecated-removed:: 3.11 3.15
diff --git a/Doc/c-api/intro.rst b/Doc/c-api/intro.rst
index 9828e537a90654..c3a80234f86116 100644
--- a/Doc/c-api/intro.rst
+++ b/Doc/c-api/intro.rst
@@ -123,6 +123,7 @@ System includes
* ````
* ````
* ````
+ * ````
* ````
* ```` (if present)
@@ -138,7 +139,6 @@ System includes
* ````
* ````
* ````
- * ````
.. note::
@@ -156,68 +156,6 @@ defined closer to where they are useful (for example, :c:macro:`Py_RETURN_NONE`,
Others of a more general utility are defined here. This is not necessarily a
complete listing.
-
-.. c:macro:: Py_ABS(x)
-
- Return the absolute value of ``x``.
-
- If the result cannot be represented (for example, if ``x`` has
- :c:macro:`!INT_MIN` value for :c:expr:`int` type), the behavior is
- undefined.
-
- .. versionadded:: 3.3
-
-.. c:macro:: Py_ALIGNED(num)
-
- Specify alignment to *num* bytes on compilers that support it.
-
- Consider using the C11 standard ``_Alignas`` specifier over this macro.
-
-.. c:macro:: Py_ARITHMETIC_RIGHT_SHIFT(type, integer, positions)
-
- Similar to ``integer >> positions``, but forces sign extension, as the C
- standard does not define whether a right-shift of a signed integer will
- perform sign extension or a zero-fill.
-
- *integer* should be any signed integer type.
- *positions* is the number of positions to shift to the right.
-
- Both *integer* and *positions* can be evaluated more than once;
- consequently, avoid directly passing a function call or some other
- operation with side-effects to this macro. Instead, store the result as a
- variable and then pass it.
-
- *type* is unused and only kept for backwards compatibility. Historically,
- *type* was used to cast *integer*.
-
- .. versionchanged:: 3.1
-
- This macro is now valid for all signed integer types, not just those for
- which ``unsigned type`` is legal. As a result, *type* is no longer
- used.
-
-.. c:macro:: Py_ALWAYS_INLINE
-
- Ask the compiler to always inline a static inline function. The compiler can
- ignore it and decide to not inline the function.
-
- It can be used to inline performance critical static inline functions when
- building Python in debug mode with function inlining disabled. For example,
- MSC disables function inlining when building in debug mode.
-
- Marking blindly a static inline function with Py_ALWAYS_INLINE can result in
- worse performances (due to increased code size for example). The compiler is
- usually smarter than the developer for the cost/benefit analysis.
-
- If Python is :ref:`built in debug mode ` (if the :c:macro:`Py_DEBUG`
- macro is defined), the :c:macro:`Py_ALWAYS_INLINE` macro does nothing.
-
- It must be specified before the function return type. Usage::
-
- static inline Py_ALWAYS_INLINE int random(void) { return 4; }
-
- .. versionadded:: 3.11
-
.. c:macro:: Py_CAN_START_THREADS
If this macro is defined, then the current system is able to start threads.
@@ -227,139 +165,143 @@ complete listing.
.. versionadded:: 3.13
-.. c:macro:: Py_CHARMASK(c)
-
- Argument must be a character or an integer in the range [-128, 127] or [0,
- 255]. This macro returns ``c`` cast to an ``unsigned char``.
-
-.. c:macro:: Py_DEPRECATED(version)
+.. c:macro:: Py_GETENV(s)
- Use this for deprecated declarations. The macro must be placed before the
- symbol name.
+ Like :samp:`getenv({s})`, but returns ``NULL`` if :option:`-E` was passed
+ on the command line (see :c:member:`PyConfig.use_environment`).
- Example::
- Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
+Docstring macros
+----------------
- .. versionchanged:: 3.8
- MSVC support was added.
+.. c:macro:: PyDoc_STRVAR(name, str)
-.. c:macro:: Py_FORCE_EXPANSION(X)
+ Creates a variable with name *name* that can be used in docstrings.
+ If Python is built without docstrings (:option:`--without-doc-strings`),
+ the value will be an empty string.
- This is equivalent to ``X``, which is useful for token-pasting in
- macros, as macro expansions in *X* are forcefully evaluated by the
- preprocessor.
+ Example::
-.. c:macro:: Py_GCC_ATTRIBUTE(name)
+ PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
- Use a GCC attribute *name*, hiding it from compilers that don't support GCC
- attributes (such as MSVC).
+ static PyMethodDef deque_methods[] = {
+ // ...
+ {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
+ // ...
+ }
- This expands to ``__attribute__((name))`` on a GCC compiler, and expands
- to nothing on compilers that don't support GCC attributes.
+ Expands to :samp:`PyDoc_VAR({name}) = PyDoc_STR({str})`.
-.. c:macro:: Py_GETENV(s)
+.. c:macro:: PyDoc_STR(str)
- Like ``getenv(s)``, but returns ``NULL`` if :option:`-E` was passed on the
- command line (see :c:member:`PyConfig.use_environment`).
+ Expands to the given input string, or an empty string
+ if docstrings are disabled (:option:`--without-doc-strings`).
-.. c:macro:: Py_LL(number)
+ Example::
- Use *number* as a ``long long`` integer literal.
+ static PyMethodDef pysqlite_row_methods[] = {
+ {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
+ PyDoc_STR("Returns the keys of the row.")},
+ {NULL, NULL}
+ };
- This usally expands to *number* followed by ``LL``, but will expand to some
- compiler-specific suffixes (such as ``I64``) on older compilers.
+.. c:macro:: PyDoc_VAR(name)
- In modern versions of Python, this macro is not very useful, as C99 and
- later require the ``LL`` suffix to be valid for an integer.
+ Declares a static character array variable with the given *name*.
+ Expands to :samp:`static const char {name}[]`
-.. c:macro:: Py_LOCAL(type)
+ For example::
- Declare a function returning the specified *type* using a fast-calling
- qualifier for functions that are local to the current file.
- Semantically, this is equivalent to ``static type``.
+ PyDoc_VAR(python_doc) = PyDoc_STR(
+ "A genus of constricting snakes in the Pythonidae family native "
+ "to the tropics and subtropics of the Eastern Hemisphere.");
-.. c:macro:: Py_LOCAL_INLINE(type)
- Equivalent to :c:macro:`Py_LOCAL` but additionally requests the function
- be inlined.
+General utility macros
+----------------------
-.. c:macro:: Py_LOCAL_SYMBOL
+The following macros are for common tasks not specific to Python.
- Macro used to declare a symbol as local to the shared library (hidden).
- On supported platforms, it ensures the symbol is not exported.
+.. c:macro:: Py_UNUSED(arg)
- On compatible versions of GCC/Clang, it
- expands to ``__attribute__((visibility("hidden")))``.
+ Use this for unused arguments in a function definition to silence compiler
+ warnings. Example: ``int func(int a, int Py_UNUSED(b)) { return a; }``.
-.. c:macro:: Py_MAX(x, y)
+ .. versionadded:: 3.4
- Return the maximum value between ``x`` and ``y``.
+.. c:macro:: Py_GCC_ATTRIBUTE(name)
- .. versionadded:: 3.3
+ Use a GCC attribute *name*, hiding it from compilers that don't support GCC
+ attributes (such as MSVC).
-.. c:macro:: Py_MEMBER_SIZE(type, member)
+ This expands to :samp:`__attribute__(({name)})` on a GCC compiler,
+ and expands to nothing on compilers that don't support GCC attributes.
- Return the size of a structure (``type``) ``member`` in bytes.
- .. versionadded:: 3.6
+Numeric utilities
+^^^^^^^^^^^^^^^^^
-.. c:macro:: Py_MEMCPY(dest, src, n)
+.. c:macro:: Py_ABS(x)
- This is a :term:`soft deprecated` alias to :c:func:`!memcpy`.
- Use :c:func:`!memcpy` directly instead.
+ Return the absolute value of ``x``.
- .. deprecated:: 3.14
- The macro is :term:`soft deprecated`.
+ The argument may be evaluated more than once.
+ Consequently, do not pass an expression with side-effects directly
+ to this macro.
-.. c:macro:: Py_MIN(x, y)
+ If the result cannot be represented (for example, if ``x`` has
+ :c:macro:`!INT_MIN` value for :c:expr:`int` type), the behavior is
+ undefined.
- Return the minimum value between ``x`` and ``y``.
+ Corresponds roughly to :samp:`(({x}) < 0 ? -({x}) : ({x}))`
.. versionadded:: 3.3
-.. c:macro:: Py_NO_INLINE
+.. c:macro:: Py_MAX(x, y)
+ Py_MIN(x, y)
- Disable inlining on a function. For example, it reduces the C stack
- consumption: useful on LTO+PGO builds which heavily inline code (see
- :issue:`33720`).
+ Return the larger or smaller of the arguments, respectively.
- Usage::
+ Any arguments may be evaluated more than once.
+ Consequently, do not pass an expression with side-effects directly
+ to this macro.
- Py_NO_INLINE static int random(void) { return 4; }
+ :c:macro:`!Py_MAX` corresponds roughly to
+ :samp:`((({x}) > ({y})) ? ({x}) : ({y}))`.
- .. versionadded:: 3.11
+ .. versionadded:: 3.3
-.. c:macro:: Py_SAFE_DOWNCAST(value, larger, smaller)
+.. c:macro:: Py_ARITHMETIC_RIGHT_SHIFT(type, integer, positions)
- Cast *value* to type *smaller* from type *larger*, validating that no
- information was lost.
+ Similar to :samp:`{integer} >> {positions}`, but forces sign extension,
+ as the C standard does not define whether a right-shift of a signed
+ integer will perform sign extension or a zero-fill.
- On release builds of Python, this is roughly equivalent to
- ``(smaller) value`` (in C++, ``static_cast(value)`` will be
- used instead).
+ *integer* should be any signed integer type.
+ *positions* is the number of positions to shift to the right.
- On debug builds (implying that :c:macro:`Py_DEBUG` is defined), this asserts
- that no information was lost with the cast from *larger* to *smaller*.
+ Both *integer* and *positions* can be evaluated more than once;
+ consequently, avoid directly passing a function call or some other
+ operation with side-effects to this macro. Instead, store the result as a
+ variable and then pass it.
- *value*, *larger*, and *smaller* may all be evaluated more than once in the
- expression; consequently, do not pass an expression with side-effects directly to
- this macro.
+ *type* is unused and only kept for backwards compatibility. Historically,
+ *type* was used to cast *integer*.
-.. c:macro:: Py_STRINGIFY(x)
+ .. versionchanged:: 3.1
- Convert ``x`` to a C string. E.g. ``Py_STRINGIFY(123)`` returns
- ``"123"``.
+ This macro is now valid for all signed integer types, not just those for
+ which ``unsigned type`` is legal. As a result, *type* is no longer
+ used.
- .. versionadded:: 3.4
+.. c:macro:: Py_CHARMASK(c)
-.. c:macro:: Py_ULL(number)
+ Argument must be a character or an integer in the range [-128, 127] or [0,
+ 255]. This macro returns ``c`` cast to an ``unsigned char``.
- Similar to :c:macro:`Py_LL`, but *number* will be an ``unsigned long long``
- literal instead. This is done by appending ``U`` to the result of ``Py_LL``.
- In modern versions of Python, this macro is not very useful, as C99 and
- later require the ``ULL``/``LLU`` suffixes to be valid for an integer.
+Assertion utilities
+^^^^^^^^^^^^^^^^^^^
.. c:macro:: Py_UNREACHABLE()
@@ -372,8 +314,11 @@ complete listing.
avoids a warning about unreachable code. For example, the macro is
implemented with ``__builtin_unreachable()`` on GCC in release mode.
- A use for ``Py_UNREACHABLE()`` is following a call a function that
- never returns but that is not declared :c:macro:`_Py_NO_RETURN`.
+ In debug mode, and on unsupported compilers, the macro expands to a call to
+ :c:func:`Py_FatalError`.
+
+ A use for ``Py_UNREACHABLE()`` is following a call to a function that
+ never returns but that is not declared ``_Noreturn``.
If a code path is very unlikely code but can be reached under exceptional
case, this macro must not be used. For example, under low memory condition
@@ -383,18 +328,29 @@ complete listing.
.. versionadded:: 3.7
-.. c:macro:: Py_UNUSED(arg)
+.. c:macro:: Py_SAFE_DOWNCAST(value, larger, smaller)
- Use this for unused arguments in a function definition to silence compiler
- warnings. Example: ``int func(int a, int Py_UNUSED(b)) { return a; }``.
+ Cast *value* to type *smaller* from type *larger*, validating that no
+ information was lost.
- .. versionadded:: 3.4
+ On release builds of Python, this is roughly equivalent to
+ :samp:`(({smaller}) {value})`
+ (in C++, :samp:`static_cast<{smaller}>({value})` will be used instead).
+
+ On debug builds (implying that :c:macro:`Py_DEBUG` is defined), this asserts
+ that no information was lost with the cast from *larger* to *smaller*.
+
+ *value*, *larger*, and *smaller* may all be evaluated more than once in the
+ expression; consequently, do not pass an expression with side-effects
+ directly to this macro.
.. c:macro:: Py_BUILD_ASSERT(cond)
Asserts a compile-time condition *cond*, as a statement.
The build will fail if the condition is false or cannot be evaluated at compile time.
+ Corresponds roughly to :samp:`static_assert({cond})` on C23 and above.
+
For example::
Py_BUILD_ASSERT(sizeof(PyTime_t) == sizeof(int64_t));
@@ -413,62 +369,127 @@ complete listing.
.. versionadded:: 3.3
-.. c:macro:: PyDoc_STRVAR(name, str)
- Creates a variable with name *name* that can be used in docstrings.
- If Python is built without docstrings, the value will be empty.
+Type size utilities
+^^^^^^^^^^^^^^^^^^^
- Use :c:macro:`PyDoc_STRVAR` for docstrings to support building
- Python without docstrings, as specified in :pep:`7`.
+.. c:macro:: Py_ARRAY_LENGTH(array)
- Example::
+ Compute the length of a statically allocated C array at compile time.
- PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
+ The *array* argument must be a C array with a size known at compile time.
+ Passing an array with an unknown size, such as a heap-allocated array,
+ will result in a compilation error on some compilers, or otherwise produce
+ incorrect results.
- static PyMethodDef deque_methods[] = {
- // ...
- {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
- // ...
- }
+ This is roughly equivalent to::
-.. c:macro:: PyDoc_STR(str)
+ sizeof(array) / sizeof((array)[0])
- Creates a docstring for the given input string or an empty string
- if docstrings are disabled.
+.. c:macro:: Py_MEMBER_SIZE(type, member)
- Use :c:macro:`PyDoc_STR` in specifying docstrings to support
- building Python without docstrings, as specified in :pep:`7`.
+ Return the size of a structure (*type*) *member* in bytes.
- Example::
+ Corresponds roughly to :samp:`sizeof((({type} *)NULL)->{member})`.
- static PyMethodDef pysqlite_row_methods[] = {
- {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
- PyDoc_STR("Returns the keys of the row.")},
- {NULL, NULL}
- };
+ .. versionadded:: 3.6
-.. c:macro:: PyDoc_VAR(name)
- Declares a static character array variable with the given name *name*.
+Macro definition utilities
+^^^^^^^^^^^^^^^^^^^^^^^^^^
- For example::
+.. c:macro:: Py_FORCE_EXPANSION(X)
- PyDoc_VAR(python_doc) = PyDoc_STR("A genus of constricting snakes in the Pythonidae family native "
- "to the tropics and subtropics of the Eastern Hemisphere.");
+ This is equivalent to :samp:`{X}`, which is useful for token-pasting in
+ macros, as macro expansions in *X* are forcefully evaluated by the
+ preprocessor.
-.. c:macro:: Py_ARRAY_LENGTH(array)
+.. c:macro:: Py_STRINGIFY(x)
- Compute the length of a statically allocated C array at compile time.
+ Convert ``x`` to a C string. For example, ``Py_STRINGIFY(123)`` returns
+ ``"123"``.
- The *array* argument must be a C array with a size known at compile time.
- Passing an array with an unknown size, such as a heap-allocated array,
- will result in a compilation error on some compilers, or otherwise produce
- incorrect results.
+ .. versionadded:: 3.4
- This is roughly equivalent to::
- sizeof(array) / sizeof((array)[0])
+Declaration utilities
+---------------------
+
+The following macros can be used in declarations.
+They are most useful for defining the C API itself, and have limited use
+for extension authors.
+Most of them expand to compiler-specific spellings of common extensions
+to the C language.
+.. c:macro:: Py_ALWAYS_INLINE
+
+ Ask the compiler to always inline a static inline function. The compiler can
+ ignore it and decide to not inline the function.
+
+ Corresponds to ``always_inline`` attribute in GCC and ``__forceinline``
+ in MSVC.
+
+ It can be used to inline performance critical static inline functions when
+ building Python in debug mode with function inlining disabled. For example,
+ MSC disables function inlining when building in debug mode.
+
+ Marking blindly a static inline function with Py_ALWAYS_INLINE can result in
+ worse performances (due to increased code size for example). The compiler is
+ usually smarter than the developer for the cost/benefit analysis.
+
+ If Python is :ref:`built in debug mode ` (if the :c:macro:`Py_DEBUG`
+ macro is defined), the :c:macro:`Py_ALWAYS_INLINE` macro does nothing.
+
+ It must be specified before the function return type. Usage::
+
+ static inline Py_ALWAYS_INLINE int random(void) { return 4; }
+
+ .. versionadded:: 3.11
+
+.. c:macro:: Py_NO_INLINE
+
+ Disable inlining on a function. For example, it reduces the C stack
+ consumption: useful on LTO+PGO builds which heavily inline code (see
+ :issue:`33720`).
+
+ Corresponds to the ``noinline`` attribute/specification on GCC and MSVC.
+
+ Usage::
+
+ Py_NO_INLINE static int random(void) { return 4; }
+
+ .. versionadded:: 3.11
+
+.. c:macro:: Py_DEPRECATED(version)
+
+ Use this to declare APIs that were deprecated in a specific CPython version.
+ The macro must be placed before the symbol name.
+
+ Example::
+
+ Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
+
+ .. versionchanged:: 3.8
+ MSVC support was added.
+
+.. c:macro:: Py_LOCAL(type)
+
+ Declare a function returning the specified *type* using a fast-calling
+ qualifier for functions that are local to the current file.
+ Semantically, this is equivalent to :samp:`static {type}`.
+
+.. c:macro:: Py_LOCAL_INLINE(type)
+
+ Equivalent to :c:macro:`Py_LOCAL` but additionally requests the function
+ be inlined.
+
+.. c:macro:: Py_LOCAL_SYMBOL
+
+ Macro used to declare a symbol as local to the shared library (hidden).
+ On supported platforms, it ensures the symbol is not exported.
+
+ On compatible versions of GCC/Clang, it
+ expands to ``__attribute__((visibility("hidden")))``.
.. c:macro:: Py_EXPORTED_SYMBOL
@@ -501,6 +522,38 @@ complete listing.
This macro is intended for defining CPython's C API itself;
extension modules should not use it for their own symbols.
+
+Outdated macros
+---------------
+
+The following macros have been used to features that have been standardized
+in C11.
+
+.. c:macro:: Py_ALIGNED(num)
+
+ Specify alignment to *num* bytes on compilers that support it.
+
+ Consider using the C11 standard ``_Alignas`` specifier over this macro.
+
+.. c:macro:: Py_LL(number)
+ Py_ULL(number)
+
+ Use *number* as a ``long long`` or ``unsigned long long`` integer literal,
+ respectively.
+
+ Expands to *number* followed by ``LL`` or ``LLU``, respectively, but will
+ expand to some compiler-specific suffixes on some older compilers.
+
+ Consider using the C99 standard suffixes ``LL`` and ``LLU`` directly.
+
+.. c:macro:: Py_MEMCPY(dest, src, n)
+
+ This is a :term:`soft deprecated` alias to :c:func:`!memcpy`.
+ Use :c:func:`!memcpy` directly instead.
+
+ .. deprecated:: 3.14
+ The macro is :term:`soft deprecated`.
+
.. c:macro:: Py_VA_COPY
This is a :term:`soft deprecated` alias to the C99-standard ``va_copy``
diff --git a/Doc/c-api/memory.rst b/Doc/c-api/memory.rst
index 58f0de5d0fc541..9f84e4bc6dfd91 100644
--- a/Doc/c-api/memory.rst
+++ b/Doc/c-api/memory.rst
@@ -7,10 +7,6 @@
Memory Management
*****************
-.. sectionauthor:: Vladimir Marangozov
-
-
-
.. _memoryoverview:
Overview
@@ -208,8 +204,11 @@ The following function sets, modeled after the ANSI C standard, but specifying
behavior when requesting zero bytes, are available for allocating and releasing
memory from the Python heap.
-The :ref:`default memory allocator ` uses the
-:ref:`pymalloc memory allocator `.
+In the GIL-enabled build (default build) the
+:ref:`default memory allocator ` uses the
+:ref:`pymalloc memory allocator `, whereas in the
+:term:`free-threaded build`, the default is the
+:ref:`mimalloc memory allocator ` instead.
.. warning::
@@ -219,6 +218,11 @@ The :ref:`default memory allocator ` uses the
The default allocator is now pymalloc instead of system :c:func:`malloc`.
+.. versionchanged:: 3.13
+
+ In the :term:`free-threaded ` build, the default allocator
+ is now :ref:`mimalloc `.
+
.. c:function:: void* PyMem_Malloc(size_t n)
Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the
@@ -344,7 +348,9 @@ memory from the Python heap.
the :ref:`Customize Memory Allocators ` section.
The :ref:`default object allocator ` uses the
-:ref:`pymalloc memory allocator `.
+:ref:`pymalloc memory allocator `. In the
+:term:`free-threaded ` build, the default is the
+:ref:`mimalloc memory allocator ` instead.
.. warning::
@@ -424,14 +430,16 @@ Default Memory Allocators
Default memory allocators:
-=============================== ==================== ================== ===================== ====================
-Configuration Name PyMem_RawMalloc PyMem_Malloc PyObject_Malloc
-=============================== ==================== ================== ===================== ====================
-Release build ``"pymalloc"`` ``malloc`` ``pymalloc`` ``pymalloc``
-Debug build ``"pymalloc_debug"`` ``malloc`` + debug ``pymalloc`` + debug ``pymalloc`` + debug
-Release build, without pymalloc ``"malloc"`` ``malloc`` ``malloc`` ``malloc``
-Debug build, without pymalloc ``"malloc_debug"`` ``malloc`` + debug ``malloc`` + debug ``malloc`` + debug
-=============================== ==================== ================== ===================== ====================
+=================================== ======================= ==================== ====================== ======================
+Configuration Name PyMem_RawMalloc PyMem_Malloc PyObject_Malloc
+=================================== ======================= ==================== ====================== ======================
+Release build ``"pymalloc"`` ``malloc`` ``pymalloc`` ``pymalloc``
+Debug build ``"pymalloc_debug"`` ``malloc`` + debug ``pymalloc`` + debug ``pymalloc`` + debug
+Release build, without pymalloc ``"malloc"`` ``malloc`` ``malloc`` ``malloc``
+Debug build, without pymalloc ``"malloc_debug"`` ``malloc`` + debug ``malloc`` + debug ``malloc`` + debug
+Free-threaded build ``"mimalloc"`` ``mimalloc`` ``mimalloc`` ``mimalloc``
+Free-threaded debug build ``"mimalloc_debug"`` ``mimalloc`` + debug ``mimalloc`` + debug ``mimalloc`` + debug
+=================================== ======================= ==================== ====================== ======================
Legend:
@@ -439,8 +447,7 @@ Legend:
* ``malloc``: system allocators from the standard C library, C functions:
:c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`.
* ``pymalloc``: :ref:`pymalloc memory allocator `.
-* ``mimalloc``: :ref:`mimalloc memory allocator `. The pymalloc
- allocator will be used if mimalloc support isn't available.
+* ``mimalloc``: :ref:`mimalloc memory allocator `.
* "+ debug": with :ref:`debug hooks on the Python memory allocators
`.
* "Debug build": :ref:`Python build in debug mode `.
@@ -737,9 +744,27 @@ The mimalloc allocator
.. versionadded:: 3.13
-Python supports the mimalloc allocator when the underlying platform support is available.
-mimalloc "is a general purpose allocator with excellent performance characteristics.
-Initially developed by Daan Leijen for the runtime systems of the Koka and Lean languages."
+Python supports the `mimalloc `__
+allocator when the underlying platform support is available.
+mimalloc is a general purpose allocator with excellent performance
+characteristics, initially developed by Daan Leijen for the runtime systems
+of the Koka and Lean languages.
+
+Unlike :ref:`pymalloc `, which is optimized for small objects (512
+bytes or fewer), mimalloc handles allocations of any size.
+
+In the :term:`free-threaded ` build, mimalloc is the default
+and **required** allocator for the :c:macro:`PYMEM_DOMAIN_MEM` and
+:c:macro:`PYMEM_DOMAIN_OBJ` domains. It cannot be disabled in free-threaded
+builds. The free-threaded build uses per-thread mimalloc heaps, which allows
+allocation and deallocation to proceed without locking in most cases.
+
+In the default (non-free-threaded) build, mimalloc is available but not the
+default allocator. It can be selected at runtime using
+:envvar:`PYTHONMALLOC`\ ``=mimalloc`` (or ``mimalloc_debug`` to include
+:ref:`debug hooks `). It can be disabled at build time
+using the :option:`--without-mimalloc` configure option, but this option
+cannot be combined with :option:`--disable-gil`.
tracemalloc C API
=================
diff --git a/Doc/c-api/module.rst b/Doc/c-api/module.rst
index e8a6e09f5554ec..39293b0fa228df 100644
--- a/Doc/c-api/module.rst
+++ b/Doc/c-api/module.rst
@@ -725,10 +725,11 @@ remove it.
An array of additional slots, terminated by a ``{0, NULL}`` entry.
- This array may not contain slots corresponding to :c:type:`PyModuleDef`
- members.
- For example, you cannot use :c:macro:`Py_mod_name` in :c:member:`!m_slots`;
- the module name must be given as :c:member:`PyModuleDef.m_name`.
+ If the array contains slots corresponding to :c:type:`PyModuleDef`
+ members, the values must match.
+ For example, if you use :c:macro:`Py_mod_name` in :c:member:`!m_slots`,
+ :c:member:`PyModuleDef.m_name` must be set to the same pointer
+ (not just an equal string).
.. versionchanged:: 3.5
@@ -751,7 +752,12 @@ remove it.
.. versionchanged:: 3.9
:c:member:`m_traverse`, :c:member:`m_clear` and :c:member:`m_free`
- functions are longer called before the module state is allocated.
+ functions are no longer called before the module state is allocated.
+
+
+.. c:var:: PyTypeObject PyModuleDef_Type
+
+ The type of ``PyModuleDef`` objects.
.. _moduledef-dynamic:
diff --git a/Doc/c-api/object.rst b/Doc/c-api/object.rst
index 992a4383f97241..15a4b55eab82f0 100644
--- a/Doc/c-api/object.rst
+++ b/Doc/c-api/object.rst
@@ -801,3 +801,20 @@ Object Protocol
cannot fail.
.. versionadded:: 3.14
+
+.. c:function:: int PyUnstable_SetImmortal(PyObject *op)
+
+ Marks the object *op* :term:`immortal`. The argument should be uniquely referenced by
+ the calling thread. This is intended to be used for reducing reference counting contention
+ in the :term:`free-threaded build` for objects which are shared across threads.
+
+ This is a one-way process: objects can only be made immortal; they cannot be
+ made mortal once again. Immortal objects do not participate in reference counting
+ and will never be garbage collected. If the object is GC-tracked, it is untracked.
+
+ This function is intended to be used soon after *op* is created, by the code that
+ creates it, such as in the object's :c:member:`~PyTypeObject.tp_new` slot.
+ Returns 1 if the object was made immortal and returns 0 if it was not.
+ This function cannot fail.
+
+ .. versionadded:: 3.15
diff --git a/Doc/c-api/profiling.rst b/Doc/c-api/profiling.rst
new file mode 100644
index 00000000000000..0200f2eac6d908
--- /dev/null
+++ b/Doc/c-api/profiling.rst
@@ -0,0 +1,239 @@
+.. highlight:: c
+
+.. _profiling:
+
+Profiling and tracing
+=====================
+
+The Python interpreter provides some low-level support for attaching profiling
+and execution tracing facilities. These are used for profiling, debugging, and
+coverage analysis tools.
+
+This C interface allows the profiling or tracing code to avoid the overhead of
+calling through Python-level callable objects, making a direct C function call
+instead. The essential attributes of the facility have not changed; the
+interface allows trace functions to be installed per-thread, and the basic
+events reported to the trace function are the same as had been reported to the
+Python-level trace functions in previous versions.
+
+
+.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
+
+ The type of the trace function registered using :c:func:`PyEval_SetProfile` and
+ :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the
+ registration function as *obj*, *frame* is the frame object to which the event
+ pertains, *what* is one of the constants :c:data:`PyTrace_CALL`,
+ :c:data:`PyTrace_EXCEPTION`, :c:data:`PyTrace_LINE`, :c:data:`PyTrace_RETURN`,
+ :c:data:`PyTrace_C_CALL`, :c:data:`PyTrace_C_EXCEPTION`, :c:data:`PyTrace_C_RETURN`,
+ or :c:data:`PyTrace_OPCODE`, and *arg* depends on the value of *what*:
+
+ +-------------------------------+----------------------------------------+
+ | Value of *what* | Meaning of *arg* |
+ +===============================+========================================+
+ | :c:data:`PyTrace_CALL` | Always :c:data:`Py_None`. |
+ +-------------------------------+----------------------------------------+
+ | :c:data:`PyTrace_EXCEPTION` | Exception information as returned by |
+ | | :func:`sys.exc_info`. |
+ +-------------------------------+----------------------------------------+
+ | :c:data:`PyTrace_LINE` | Always :c:data:`Py_None`. |
+ +-------------------------------+----------------------------------------+
+ | :c:data:`PyTrace_RETURN` | Value being returned to the caller, |
+ | | or ``NULL`` if caused by an exception. |
+ +-------------------------------+----------------------------------------+
+ | :c:data:`PyTrace_C_CALL` | Function object being called. |
+ +-------------------------------+----------------------------------------+
+ | :c:data:`PyTrace_C_EXCEPTION` | Function object being called. |
+ +-------------------------------+----------------------------------------+
+ | :c:data:`PyTrace_C_RETURN` | Function object being called. |
+ +-------------------------------+----------------------------------------+
+ | :c:data:`PyTrace_OPCODE` | Always :c:data:`Py_None`. |
+ +-------------------------------+----------------------------------------+
+
+.. c:var:: int PyTrace_CALL
+
+ The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new
+ call to a function or method is being reported, or a new entry into a generator.
+ Note that the creation of the iterator for a generator function is not reported
+ as there is no control transfer to the Python bytecode in the corresponding
+ frame.
+
+
+.. c:var:: int PyTrace_EXCEPTION
+
+ The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an
+ exception has been raised. The callback function is called with this value for
+ *what* when after any bytecode is processed after which the exception becomes
+ set within the frame being executed. The effect of this is that as exception
+ propagation causes the Python stack to unwind, the callback is called upon
+ return to each frame as the exception propagates. Only trace functions receive
+ these events; they are not needed by the profiler.
+
+
+.. c:var:: int PyTrace_LINE
+
+ The value passed as the *what* parameter to a :c:type:`Py_tracefunc` function
+ (but not a profiling function) when a line-number event is being reported.
+ It may be disabled for a frame by setting :attr:`~frame.f_trace_lines` to
+ *0* on that frame.
+
+
+.. c:var:: int PyTrace_RETURN
+
+ The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a
+ call is about to return.
+
+
+.. c:var:: int PyTrace_C_CALL
+
+ The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
+ function is about to be called.
+
+
+.. c:var:: int PyTrace_C_EXCEPTION
+
+ The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
+ function has raised an exception.
+
+
+.. c:var:: int PyTrace_C_RETURN
+
+ The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
+ function has returned.
+
+
+.. c:var:: int PyTrace_OPCODE
+
+ The value for the *what* parameter to :c:type:`Py_tracefunc` functions (but not
+ profiling functions) when a new opcode is about to be executed. This event is
+ not emitted by default: it must be explicitly requested by setting
+ :attr:`~frame.f_trace_opcodes` to *1* on the frame.
+
+
+.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
+
+ Set the profiler function to *func*. The *obj* parameter is passed to the
+ function as its first parameter, and may be any Python object, or ``NULL``. If
+ the profile function needs to maintain state, using a different value for *obj*
+ for each thread provides a convenient and thread-safe place to store it. The
+ profile function is called for all monitored events except :c:data:`PyTrace_LINE`
+ :c:data:`PyTrace_OPCODE` and :c:data:`PyTrace_EXCEPTION`.
+
+ See also the :func:`sys.setprofile` function.
+
+ The caller must have an :term:`attached thread state`.
+
+
+.. c:function:: void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)
+
+ Like :c:func:`PyEval_SetProfile` but sets the profile function in all running threads
+ belonging to the current interpreter instead of the setting it only on the current thread.
+
+ The caller must have an :term:`attached thread state`.
+
+ As :c:func:`PyEval_SetProfile`, this function ignores any exceptions raised while
+ setting the profile functions in all threads.
+
+.. versionadded:: 3.12
+
+
+.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
+
+ Set the tracing function to *func*. This is similar to
+ :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number
+ events and per-opcode events, but does not receive any event related to C function
+ objects being called. Any trace function registered using :c:func:`PyEval_SetTrace`
+ will not receive :c:data:`PyTrace_C_CALL`, :c:data:`PyTrace_C_EXCEPTION` or
+ :c:data:`PyTrace_C_RETURN` as a value for the *what* parameter.
+
+ See also the :func:`sys.settrace` function.
+
+ The caller must have an :term:`attached thread state`.
+
+
+.. c:function:: void PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *obj)
+
+ Like :c:func:`PyEval_SetTrace` but sets the tracing function in all running threads
+ belonging to the current interpreter instead of the setting it only on the current thread.
+
+ The caller must have an :term:`attached thread state`.
+
+ As :c:func:`PyEval_SetTrace`, this function ignores any exceptions raised while
+ setting the trace functions in all threads.
+
+.. versionadded:: 3.12
+
+
+Reference tracing
+=================
+
+.. versionadded:: 3.13
+
+
+.. c:type:: int (*PyRefTracer)(PyObject *, int event, void* data)
+
+ The type of the trace function registered using :c:func:`PyRefTracer_SetTracer`.
+ The first parameter is a Python object that has been just created (when **event**
+ is set to :c:data:`PyRefTracer_CREATE`) or about to be destroyed (when **event**
+ is set to :c:data:`PyRefTracer_DESTROY`). The **data** argument is the opaque pointer
+ that was provided when :c:func:`PyRefTracer_SetTracer` was called.
+
+ If a new tracing function is registered replacing the current one, a call to the
+ trace function will be made with the object set to **NULL** and **event** set to
+ :c:data:`PyRefTracer_TRACKER_REMOVED`. This will happen just before the new
+ function is registered.
+
+.. versionadded:: 3.13
+
+
+.. c:var:: int PyRefTracer_CREATE
+
+ The value for the *event* parameter to :c:type:`PyRefTracer` functions when a Python
+ object has been created.
+
+
+.. c:var:: int PyRefTracer_DESTROY
+
+ The value for the *event* parameter to :c:type:`PyRefTracer` functions when a Python
+ object has been destroyed.
+
+
+.. c:var:: int PyRefTracer_TRACKER_REMOVED
+
+ The value for the *event* parameter to :c:type:`PyRefTracer` functions when the
+ current tracer is about to be replaced by a new one.
+
+ .. versionadded:: 3.14
+
+
+.. c:function:: int PyRefTracer_SetTracer(PyRefTracer tracer, void *data)
+
+ Register a reference tracer function. The function will be called when a new
+ Python object has been created or when an object is going to be destroyed. If
+ **data** is provided it must be an opaque pointer that will be provided when
+ the tracer function is called. Return ``0`` on success. Set an exception and
+ return ``-1`` on error.
+
+ Note that tracer functions **must not** create Python objects inside or
+ otherwise the call will be re-entrant. The tracer also **must not** clear
+ any existing exception or set an exception. A :term:`thread state` will be active
+ every time the tracer function is called.
+
+ There must be an :term:`attached thread state` when calling this function.
+
+ If another tracer function was already registered, the old function will be
+ called with **event** set to :c:data:`PyRefTracer_TRACKER_REMOVED` just before
+ the new function is registered.
+
+.. versionadded:: 3.13
+
+
+.. c:function:: PyRefTracer PyRefTracer_GetTracer(void** data)
+
+ Get the registered reference tracer function and the value of the opaque data
+ pointer that was registered when :c:func:`PyRefTracer_SetTracer` was called.
+ If no tracer was registered this function will return NULL and will set the
+ **data** pointer to NULL.
+
+ There must be an :term:`attached thread state` when calling this function.
+
+.. versionadded:: 3.13
diff --git a/Doc/c-api/set.rst b/Doc/c-api/set.rst
index b74859dd669c54..6974f74fbd597a 100644
--- a/Doc/c-api/set.rst
+++ b/Doc/c-api/set.rst
@@ -5,9 +5,6 @@
Set Objects
-----------
-.. sectionauthor:: Raymond D. Hettinger
-
-
.. index::
pair: object; set
pair: object; frozenset
diff --git a/Doc/c-api/structures.rst b/Doc/c-api/structures.rst
index 62f45def04f746..c0d2663adefc6b 100644
--- a/Doc/c-api/structures.rst
+++ b/Doc/c-api/structures.rst
@@ -48,6 +48,19 @@ under :ref:`reference counting `.
Do not use this field directly; use :c:macro:`Py_TYPE` and
:c:func:`Py_SET_TYPE` instead.
+ .. c:member:: PyMutex ob_mutex
+
+ A :ref:`per-object lock `, present only in the :term:`free-threaded `
+ build (when :c:macro:`Py_GIL_DISABLED` is defined).
+
+ This field is **reserved for use by the critical section API**
+ (:c:macro:`Py_BEGIN_CRITICAL_SECTION` / :c:macro:`Py_END_CRITICAL_SECTION`).
+ Do **not** lock it directly with ``PyMutex_Lock``; doing so can cause
+ deadlocks. If you need your own lock, add a separate :c:type:`PyMutex`
+ field to your object struct.
+
+ .. versionadded:: 3.13
+
.. c:type:: PyVarObject
@@ -410,7 +423,7 @@ There are these calling conventions:
These two constants are not used to indicate the calling convention but the
-binding when use with methods of classes. These may not be used for functions
+binding when used with methods of classes. These may not be used for functions
defined for modules. At most one of these flags may be set for any given
method.
diff --git a/Doc/c-api/subinterpreters.rst b/Doc/c-api/subinterpreters.rst
new file mode 100644
index 00000000000000..44e3fc96841aac
--- /dev/null
+++ b/Doc/c-api/subinterpreters.rst
@@ -0,0 +1,470 @@
+.. highlight:: c
+
+.. _sub-interpreter-support:
+
+Multiple interpreters in a Python process
+=========================================
+
+While in most uses, you will only embed a single Python interpreter, there
+are cases where you need to create several independent interpreters in the
+same process and perhaps even in the same thread. Sub-interpreters allow
+you to do that.
+
+The "main" interpreter is the first one created when the runtime initializes.
+It is usually the only Python interpreter in a process. Unlike sub-interpreters,
+the main interpreter has unique process-global responsibilities like signal
+handling. It is also responsible for execution during runtime initialization and
+is usually the active interpreter during runtime finalization. The
+:c:func:`PyInterpreterState_Main` function returns a pointer to its state.
+
+You can switch between sub-interpreters using the :c:func:`PyThreadState_Swap`
+function. You can create and destroy them using the following functions:
+
+
+.. c:type:: PyInterpreterConfig
+
+ Structure containing most parameters to configure a sub-interpreter.
+ Its values are used only in :c:func:`Py_NewInterpreterFromConfig` and
+ never modified by the runtime.
+
+ .. versionadded:: 3.12
+
+ Structure fields:
+
+ .. c:member:: int use_main_obmalloc
+
+ If this is ``0`` then the sub-interpreter will use its own
+ "object" allocator state.
+ Otherwise it will use (share) the main interpreter's.
+
+ If this is ``0`` then
+ :c:member:`~PyInterpreterConfig.check_multi_interp_extensions`
+ must be ``1`` (non-zero).
+ If this is ``1`` then :c:member:`~PyInterpreterConfig.gil`
+ must not be :c:macro:`PyInterpreterConfig_OWN_GIL`.
+
+ .. c:member:: int allow_fork
+
+ If this is ``0`` then the runtime will not support forking the
+ process in any thread where the sub-interpreter is currently active.
+ Otherwise fork is unrestricted.
+
+ Note that the :mod:`subprocess` module still works
+ when fork is disallowed.
+
+ .. c:member:: int allow_exec
+
+ If this is ``0`` then the runtime will not support replacing the
+ current process via exec (e.g. :func:`os.execv`) in any thread
+ where the sub-interpreter is currently active.
+ Otherwise exec is unrestricted.
+
+ Note that the :mod:`subprocess` module still works
+ when exec is disallowed.
+
+ .. c:member:: int allow_threads
+
+ If this is ``0`` then the sub-interpreter's :mod:`threading` module
+ won't create threads.
+ Otherwise threads are allowed.
+
+ .. c:member:: int allow_daemon_threads
+
+ If this is ``0`` then the sub-interpreter's :mod:`threading` module
+ won't create daemon threads.
+ Otherwise daemon threads are allowed (as long as
+ :c:member:`~PyInterpreterConfig.allow_threads` is non-zero).
+
+ .. c:member:: int check_multi_interp_extensions
+
+ If this is ``0`` then all extension modules may be imported,
+ including legacy (single-phase init) modules,
+ in any thread where the sub-interpreter is currently active.
+ Otherwise only multi-phase init extension modules
+ (see :pep:`489`) may be imported.
+ (Also see :c:macro:`Py_mod_multiple_interpreters`.)
+
+ This must be ``1`` (non-zero) if
+ :c:member:`~PyInterpreterConfig.use_main_obmalloc` is ``0``.
+
+ .. c:member:: int gil
+
+ This determines the operation of the GIL for the sub-interpreter.
+ It may be one of the following:
+
+ .. c:namespace:: NULL
+
+ .. c:macro:: PyInterpreterConfig_DEFAULT_GIL
+
+ Use the default selection (:c:macro:`PyInterpreterConfig_SHARED_GIL`).
+
+ .. c:macro:: PyInterpreterConfig_SHARED_GIL
+
+ Use (share) the main interpreter's GIL.
+
+ .. c:macro:: PyInterpreterConfig_OWN_GIL
+
+ Use the sub-interpreter's own GIL.
+
+ If this is :c:macro:`PyInterpreterConfig_OWN_GIL` then
+ :c:member:`PyInterpreterConfig.use_main_obmalloc` must be ``0``.
+
+
+.. c:function:: PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)
+
+ .. index::
+ pair: module; builtins
+ pair: module; __main__
+ pair: module; sys
+ single: stdout (in module sys)
+ single: stderr (in module sys)
+ single: stdin (in module sys)
+
+ Create a new sub-interpreter. This is an (almost) totally separate environment
+ for the execution of Python code. In particular, the new interpreter has
+ separate, independent versions of all imported modules, including the
+ fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The
+ table of loaded modules (``sys.modules``) and the module search path
+ (``sys.path``) are also separate. The new environment has no ``sys.argv``
+ variable. It has new standard I/O stream file objects ``sys.stdin``,
+ ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
+ file descriptors).
+
+ The given *config* controls the options with which the interpreter
+ is initialized.
+
+ Upon success, *tstate_p* will be set to the first :term:`thread state`
+ created in the new sub-interpreter. This thread state is
+ :term:`attached `.
+ Note that no actual thread is created; see the discussion of thread states
+ below. If creation of the new interpreter is unsuccessful,
+ *tstate_p* is set to ``NULL``;
+ no exception is set since the exception state is stored in the
+ :term:`attached thread state`, which might not exist.
+
+ Like all other Python/C API functions, an :term:`attached thread state`
+ must be present before calling this function, but it might be detached upon
+ returning. On success, the returned thread state will be :term:`attached `.
+ If the sub-interpreter is created with its own :term:`GIL` then the
+ :term:`attached thread state` of the calling interpreter will be detached.
+ When the function returns, the new interpreter's :term:`thread state`
+ will be :term:`attached ` to the current thread and
+ the previous interpreter's :term:`attached thread state` will remain detached.
+
+ .. versionadded:: 3.12
+
+ Sub-interpreters are most effective when isolated from each other,
+ with certain functionality restricted::
+
+ PyInterpreterConfig config = {
+ .use_main_obmalloc = 0,
+ .allow_fork = 0,
+ .allow_exec = 0,
+ .allow_threads = 1,
+ .allow_daemon_threads = 0,
+ .check_multi_interp_extensions = 1,
+ .gil = PyInterpreterConfig_OWN_GIL,
+ };
+ PyThreadState *tstate = NULL;
+ PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
+ if (PyStatus_Exception(status)) {
+ Py_ExitStatusException(status);
+ }
+
+ Note that the config is used only briefly and does not get modified.
+ During initialization the config's values are converted into various
+ :c:type:`PyInterpreterState` values. A read-only copy of the config
+ may be stored internally on the :c:type:`PyInterpreterState`.
+
+ .. index::
+ single: Py_FinalizeEx (C function)
+ single: Py_Initialize (C function)
+
+ Extension modules are shared between (sub-)interpreters as follows:
+
+ * For modules using multi-phase initialization,
+ e.g. :c:func:`PyModule_FromDefAndSpec`, a separate module object is
+ created and initialized for each interpreter.
+ Only C-level static and global variables are shared between these
+ module objects.
+
+ * For modules using legacy
+ :ref:`single-phase initialization `,
+ e.g. :c:func:`PyModule_Create`, the first time a particular extension
+ is imported, it is initialized normally, and a (shallow) copy of its
+ module's dictionary is squirreled away.
+ When the same extension is imported by another (sub-)interpreter, a new
+ module is initialized and filled with the contents of this copy; the
+ extension's ``init`` function is not called.
+ Objects in the module's dictionary thus end up shared across
+ (sub-)interpreters, which might cause unwanted behavior (see
+ `Bugs and caveats`_ below).
+
+ Note that this is different from what happens when an extension is
+ imported after the interpreter has been completely re-initialized by
+ calling :c:func:`Py_FinalizeEx` and :c:func:`Py_Initialize`; in that
+ case, the extension's ``initmodule`` function *is* called again.
+ As with multi-phase initialization, this means that only C-level static
+ and global variables are shared between these modules.
+
+ .. index:: single: close (in module os)
+
+
+.. c:function:: PyThreadState* Py_NewInterpreter(void)
+
+ .. index::
+ pair: module; builtins
+ pair: module; __main__
+ pair: module; sys
+ single: stdout (in module sys)
+ single: stderr (in module sys)
+ single: stdin (in module sys)
+
+ Create a new sub-interpreter. This is essentially just a wrapper
+ around :c:func:`Py_NewInterpreterFromConfig` with a config that
+ preserves the existing behavior. The result is an unisolated
+ sub-interpreter that shares the main interpreter's GIL, allows
+ fork/exec, allows daemon threads, and allows single-phase init
+ modules.
+
+
+.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
+
+ .. index:: single: Py_FinalizeEx (C function)
+
+ Destroy the (sub-)interpreter represented by the given :term:`thread state`.
+ The given thread state must be :term:`attached `.
+ When the call returns, there will be no :term:`attached thread state`.
+ All thread states associated with this interpreter are destroyed.
+
+ :c:func:`Py_FinalizeEx` will destroy all sub-interpreters that
+ haven't been explicitly destroyed at that point.
+
+
+.. _per-interpreter-gil:
+
+A per-interpreter GIL
+---------------------
+
+.. versionadded:: 3.12
+
+Using :c:func:`Py_NewInterpreterFromConfig` you can create
+a sub-interpreter that is completely isolated from other interpreters,
+including having its own GIL. The most important benefit of this
+isolation is that such an interpreter can execute Python code without
+being blocked by other interpreters or blocking any others. Thus a
+single Python process can truly take advantage of multiple CPU cores
+when running Python code. The isolation also encourages a different
+approach to concurrency than that of just using threads.
+(See :pep:`554` and :pep:`684`.)
+
+Using an isolated interpreter requires vigilance in preserving that
+isolation. That especially means not sharing any objects or mutable
+state without guarantees about thread-safety. Even objects that are
+otherwise immutable (e.g. ``None``, ``(1, 5)``) can't normally be shared
+because of the refcount. One simple but less-efficient approach around
+this is to use a global lock around all use of some state (or object).
+Alternately, effectively immutable objects (like integers or strings)
+can be made safe in spite of their refcounts by making them :term:`immortal`.
+In fact, this has been done for the builtin singletons, small integers,
+and a number of other builtin objects.
+
+If you preserve isolation then you will have access to proper multi-core
+computing without the complications that come with free-threading.
+Failure to preserve isolation will expose you to the full consequences
+of free-threading, including races and hard-to-debug crashes.
+
+Aside from that, one of the main challenges of using multiple isolated
+interpreters is how to communicate between them safely (not break
+isolation) and efficiently. The runtime and stdlib do not provide
+any standard approach to this yet. A future stdlib module would help
+mitigate the effort of preserving isolation and expose effective tools
+for communicating (and sharing) data between interpreters.
+
+
+Bugs and caveats
+----------------
+
+Because sub-interpreters (and the main interpreter) are part of the same
+process, the insulation between them isn't perfect --- for example, using
+low-level file operations like :func:`os.close` they can
+(accidentally or maliciously) affect each other's open files. Because of the
+way extensions are shared between (sub-)interpreters, some extensions may not
+work properly; this is especially likely when using single-phase initialization
+or (static) global variables.
+It is possible to insert objects created in one sub-interpreter into
+a namespace of another (sub-)interpreter; this should be avoided if possible.
+
+Special care should be taken to avoid sharing user-defined functions,
+methods, instances or classes between sub-interpreters, since import
+operations executed by such objects may affect the wrong (sub-)interpreter's
+dictionary of loaded modules. It is equally important to avoid sharing
+objects from which the above are reachable.
+
+Also note that combining this functionality with ``PyGILState_*`` APIs
+is delicate, because these APIs assume a bijection between Python thread states
+and OS-level threads, an assumption broken by the presence of sub-interpreters.
+It is highly recommended that you don't switch sub-interpreters between a pair
+of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
+Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
+of Python code from non-Python created threads will probably be broken when using
+sub-interpreters.
+
+
+High-level APIs
+---------------
+
+.. c:type:: PyInterpreterState
+
+ This data structure represents the state shared by a number of cooperating
+ threads. Threads belonging to the same interpreter share their module
+ administration and a few other internal items. There are no public members in
+ this structure.
+
+ Threads belonging to different interpreters initially share nothing, except
+ process state like available memory, open file descriptors and such. The global
+ interpreter lock is also shared by all threads, regardless of to which
+ interpreter they belong.
+
+ .. versionchanged:: 3.12
+
+ :pep:`684` introduced the possibility
+ of a :ref:`per-interpreter GIL `.
+ See :c:func:`Py_NewInterpreterFromConfig`.
+
+
+.. c:function:: PyInterpreterState* PyInterpreterState_Get(void)
+
+ Get the current interpreter.
+
+ Issue a fatal error if there is no :term:`attached thread state`.
+ It cannot return NULL.
+
+ .. versionadded:: 3.9
+
+
+.. c:function:: int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
+
+ Return the interpreter's unique ID. If there was any error in doing
+ so then ``-1`` is returned and an error is set.
+
+ The caller must have an :term:`attached thread state`.
+
+ .. versionadded:: 3.7
+
+
+.. c:function:: PyObject* PyInterpreterState_GetDict(PyInterpreterState *interp)
+
+ Return a dictionary in which interpreter-specific data may be stored.
+ If this function returns ``NULL`` then no exception has been raised and
+ the caller should assume no interpreter-specific dict is available.
+
+ This is not a replacement for :c:func:`PyModule_GetState()`, which
+ extensions should use to store interpreter-specific state information.
+
+ The returned dictionary is borrowed from the interpreter and is valid until
+ interpreter shutdown.
+
+ .. versionadded:: 3.8
+
+
+.. c:type:: PyObject* (*_PyFrameEvalFunction)(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)
+
+ Type of a frame evaluation function.
+
+ The *throwflag* parameter is used by the ``throw()`` method of generators:
+ if non-zero, handle the current exception.
+
+ .. versionchanged:: 3.9
+ The function now takes a *tstate* parameter.
+
+ .. versionchanged:: 3.11
+ The *frame* parameter changed from ``PyFrameObject*`` to ``_PyInterpreterFrame*``.
+
+
+.. c:function:: _PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
+
+ Get the frame evaluation function.
+
+ See the :pep:`523` "Adding a frame evaluation API to CPython".
+
+ .. versionadded:: 3.9
+
+
+.. c:function:: void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)
+
+ Set the frame evaluation function.
+
+ See the :pep:`523` "Adding a frame evaluation API to CPython".
+
+ .. versionadded:: 3.9
+
+
+Low-level APIs
+--------------
+
+All of the following functions must be called after :c:func:`Py_Initialize`.
+
+.. versionchanged:: 3.7
+ :c:func:`Py_Initialize()` now initializes the :term:`GIL`
+ and sets an :term:`attached thread state`.
+
+
+.. c:function:: PyInterpreterState* PyInterpreterState_New()
+
+ Create a new interpreter state object. An :term:`attached thread state` is not needed,
+ but may optionally exist if it is necessary to serialize calls to this
+ function.
+
+ .. audit-event:: cpython.PyInterpreterState_New "" c.PyInterpreterState_New
+
+
+.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp)
+
+ Reset all information in an interpreter state object. There must be
+ an :term:`attached thread state` for the interpreter.
+
+ .. audit-event:: cpython.PyInterpreterState_Clear "" c.PyInterpreterState_Clear
+
+
+.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp)
+
+ Destroy an interpreter state object. There **should not** be an
+ :term:`attached thread state` for the target interpreter. The interpreter
+ state must have been reset with a previous call to :c:func:`PyInterpreterState_Clear`.
+
+
+.. _advanced-debugging:
+
+Advanced debugger support
+-------------------------
+
+These functions are only intended to be used by advanced debugging tools.
+
+
+.. c:function:: PyInterpreterState* PyInterpreterState_Head()
+
+ Return the interpreter state object at the head of the list of all such objects.
+
+
+.. c:function:: PyInterpreterState* PyInterpreterState_Main()
+
+ Return the main interpreter state object.
+
+
+.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)
+
+ Return the next interpreter state object after *interp* from the list of all
+ such objects.
+
+
+.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
+
+ Return the pointer to the first :c:type:`PyThreadState` object in the list of
+ threads associated with the interpreter *interp*.
+
+
+.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)
+
+ Return the next thread state object after *tstate* from the list of all such
+ objects belonging to the same :c:type:`PyInterpreterState` object.
diff --git a/Doc/c-api/synchronization.rst b/Doc/c-api/synchronization.rst
new file mode 100644
index 00000000000000..53c9faeae35464
--- /dev/null
+++ b/Doc/c-api/synchronization.rst
@@ -0,0 +1,308 @@
+.. highlight:: c
+
+.. _synchronization:
+
+Synchronization primitives
+==========================
+
+The C-API provides a basic mutual exclusion lock.
+
+.. c:type:: PyMutex
+
+ A mutual exclusion lock. The :c:type:`!PyMutex` should be initialized to
+ zero to represent the unlocked state. For example::
+
+ PyMutex mutex = {0};
+
+ Instances of :c:type:`!PyMutex` should not be copied or moved. Both the
+ contents and address of a :c:type:`!PyMutex` are meaningful, and it must
+ remain at a fixed, writable location in memory.
+
+ .. note::
+
+ A :c:type:`!PyMutex` currently occupies one byte, but the size should be
+ considered unstable. The size may change in future Python releases
+ without a deprecation period.
+
+ .. versionadded:: 3.13
+
+.. c:function:: void PyMutex_Lock(PyMutex *m)
+
+ Lock mutex *m*. If another thread has already locked it, the calling
+ thread will block until the mutex is unlocked. While blocked, the thread
+ will temporarily detach the :term:`thread state ` if one exists.
+
+ .. versionadded:: 3.13
+
+.. c:function:: void PyMutex_Unlock(PyMutex *m)
+
+ Unlock mutex *m*. The mutex must be locked --- otherwise, the function will
+ issue a fatal error.
+
+ .. versionadded:: 3.13
+
+.. c:function:: int PyMutex_IsLocked(PyMutex *m)
+
+ Returns non-zero if the mutex *m* is currently locked, zero otherwise.
+
+ .. note::
+
+ This function is intended for use in assertions and debugging only and
+ should not be used to make concurrency control decisions, as the lock
+ state may change immediately after the check.
+
+ .. versionadded:: 3.14
+
+.. _python-critical-section-api:
+
+Python critical section API
+---------------------------
+
+The critical section API provides a deadlock avoidance layer on top of
+per-object locks for :term:`free-threaded ` CPython. They are
+intended to replace reliance on the :term:`global interpreter lock`, and are
+no-ops in versions of Python with the global interpreter lock.
+
+Critical sections are intended to be used for custom types implemented
+in C-API extensions. They should generally not be used with built-in types like
+:class:`list` and :class:`dict` because their public C-APIs
+already use critical sections internally, with the notable
+exception of :c:func:`PyDict_Next`, which requires critical section
+to be acquired externally.
+
+Critical sections avoid deadlocks by implicitly suspending active critical
+sections, hence, they do not provide exclusive access such as provided by
+traditional locks like :c:type:`PyMutex`. When a critical section is started,
+the per-object lock for the object is acquired. If the code executed inside the
+critical section calls C-API functions then it can suspend the critical section thereby
+releasing the per-object lock, so other threads can acquire the per-object lock
+for the same object.
+
+Variants that accept :c:type:`PyMutex` pointers rather than Python objects are also
+available. Use these variants to start a critical section in a situation where
+there is no :c:type:`PyObject` -- for example, when working with a C type that
+does not extend or wrap :c:type:`PyObject` but still needs to call into the C
+API in a manner that might lead to deadlocks.
+
+The functions and structs used by the macros are exposed for cases
+where C macros are not available. They should only be used as in the
+given macro expansions. Note that the sizes and contents of the structures may
+change in future Python versions.
+
+.. note::
+
+ Operations that need to lock two objects at once must use
+ :c:macro:`Py_BEGIN_CRITICAL_SECTION2`. You *cannot* use nested critical
+ sections to lock more than one object at once, because the inner critical
+ section may suspend the outer critical sections. This API does not provide
+ a way to lock more than two objects at once.
+
+Example usage::
+
+ static PyObject *
+ set_field(MyObject *self, PyObject *value)
+ {
+ Py_BEGIN_CRITICAL_SECTION(self);
+ Py_SETREF(self->field, Py_XNewRef(value));
+ Py_END_CRITICAL_SECTION();
+ Py_RETURN_NONE;
+ }
+
+In the above example, :c:macro:`Py_SETREF` calls :c:macro:`Py_DECREF`, which
+can call arbitrary code through an object's deallocation function. The critical
+section API avoids potential deadlocks due to reentrancy and lock ordering
+by allowing the runtime to temporarily suspend the critical section if the
+code triggered by the finalizer blocks and calls :c:func:`PyEval_SaveThread`.
+
+.. c:macro:: Py_BEGIN_CRITICAL_SECTION(op)
+
+ Acquires the per-object lock for the object *op* and begins a
+ critical section.
+
+ In the free-threaded build, this macro expands to::
+
+ {
+ PyCriticalSection _py_cs;
+ PyCriticalSection_Begin(&_py_cs, (PyObject*)(op))
+
+ In the default build, this macro expands to ``{``.
+
+ .. versionadded:: 3.13
+
+.. c:macro:: Py_BEGIN_CRITICAL_SECTION_MUTEX(m)
+
+ Locks the mutex *m* and begins a critical section.
+
+ In the free-threaded build, this macro expands to::
+
+ {
+ PyCriticalSection _py_cs;
+ PyCriticalSection_BeginMutex(&_py_cs, m)
+
+ Note that unlike :c:macro:`Py_BEGIN_CRITICAL_SECTION`, there is no cast for
+ the argument of the macro - it must be a :c:type:`PyMutex` pointer.
+
+ On the default build, this macro expands to ``{``.
+
+ .. versionadded:: 3.14
+
+.. c:macro:: Py_END_CRITICAL_SECTION()
+
+ Ends the critical section and releases the per-object lock.
+
+ In the free-threaded build, this macro expands to::
+
+ PyCriticalSection_End(&_py_cs);
+ }
+
+ In the default build, this macro expands to ``}``.
+
+ .. versionadded:: 3.13
+
+.. c:macro:: Py_BEGIN_CRITICAL_SECTION2(a, b)
+
+ Acquires the per-object locks for the objects *a* and *b* and begins a
+ critical section. The locks are acquired in a consistent order (lowest
+ address first) to avoid lock ordering deadlocks.
+
+ In the free-threaded build, this macro expands to::
+
+ {
+ PyCriticalSection2 _py_cs2;
+ PyCriticalSection2_Begin(&_py_cs2, (PyObject*)(a), (PyObject*)(b))
+
+ In the default build, this macro expands to ``{``.
+
+ .. versionadded:: 3.13
+
+.. c:macro:: Py_BEGIN_CRITICAL_SECTION2_MUTEX(m1, m2)
+
+ Locks the mutexes *m1* and *m2* and begins a critical section.
+
+ In the free-threaded build, this macro expands to::
+
+ {
+ PyCriticalSection2 _py_cs2;
+ PyCriticalSection2_BeginMutex(&_py_cs2, m1, m2)
+
+ Note that unlike :c:macro:`Py_BEGIN_CRITICAL_SECTION2`, there is no cast for
+ the arguments of the macro - they must be :c:type:`PyMutex` pointers.
+
+ On the default build, this macro expands to ``{``.
+
+ .. versionadded:: 3.14
+
+.. c:macro:: Py_END_CRITICAL_SECTION2()
+
+ Ends the critical section and releases the per-object locks.
+
+ In the free-threaded build, this macro expands to::
+
+ PyCriticalSection2_End(&_py_cs2);
+ }
+
+ In the default build, this macro expands to ``}``.
+
+ .. versionadded:: 3.13
+
+
+Legacy locking APIs
+-------------------
+
+These APIs are obsolete since Python 3.13 with the introduction of
+:c:type:`PyMutex`.
+
+.. versionchanged:: 3.15
+ These APIs are now a simple wrapper around ``PyMutex``.
+
+
+.. c:type:: PyThread_type_lock
+
+ A pointer to a mutual exclusion lock.
+
+
+.. c:type:: PyLockStatus
+
+ The result of acquiring a lock with a timeout.
+
+ .. c:namespace:: NULL
+
+ .. c:enumerator:: PY_LOCK_FAILURE
+
+ Failed to acquire the lock.
+
+ .. c:enumerator:: PY_LOCK_ACQUIRED
+
+ The lock was successfully acquired.
+
+ .. c:enumerator:: PY_LOCK_INTR
+
+ The lock was interrupted by a signal.
+
+
+.. c:function:: PyThread_type_lock PyThread_allocate_lock(void)
+
+ Allocate a new lock.
+
+ On success, this function returns a lock; on failure, this
+ function returns ``0`` without an exception set.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+ .. versionchanged:: 3.15
+ This function now always uses :c:type:`PyMutex`. In prior versions, this
+ would use a lock provided by the operating system.
+
+
+.. c:function:: void PyThread_free_lock(PyThread_type_lock lock)
+
+ Destroy *lock*. The lock should not be held by any thread when calling
+ this.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: PyLockStatus PyThread_acquire_lock_timed(PyThread_type_lock lock, long long microseconds, int intr_flag)
+
+ Acquire *lock* with a timeout.
+
+ This will wait for *microseconds* microseconds to acquire the lock. If the
+ timeout expires, this function returns :c:enumerator:`PY_LOCK_FAILURE`.
+ If *microseconds* is ``-1``, this will wait indefinitely until the lock has
+ been released.
+
+ If *intr_flag* is ``1``, acquiring the lock may be interrupted by a signal,
+ in which case this function returns :c:enumerator:`PY_LOCK_INTR`. Upon
+ interruption, it's generally expected that the caller makes a call to
+ :c:func:`Py_MakePendingCalls` to propagate an exception to Python code.
+
+ If the lock is successfully acquired, this function returns
+ :c:enumerator:`PY_LOCK_ACQUIRED`.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
+
+ Acquire *lock*.
+
+ If *waitflag* is ``1`` and another thread currently holds the lock, this
+ function will wait until the lock can be acquired and will always return
+ ``1``.
+
+ If *waitflag* is ``0`` and another thread holds the lock, this function will
+ not wait and instead return ``0``. If the lock is not held by any other
+ thread, then this function will acquire it and return ``1``.
+
+ Unlike :c:func:`PyThread_acquire_lock_timed`, acquiring the lock cannot be
+ interrupted by a signal.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: int PyThread_release_lock(PyThread_type_lock lock)
+
+ Release *lock*. If *lock* is not held, then this function issues a
+ fatal error.
+
+ The caller does not need to hold an :term:`attached thread state`.
diff --git a/Doc/c-api/threads.rst b/Doc/c-api/threads.rst
new file mode 100644
index 00000000000000..3b761d0c657cbd
--- /dev/null
+++ b/Doc/c-api/threads.rst
@@ -0,0 +1,880 @@
+.. highlight:: c
+
+.. _threads:
+
+Thread states and the global interpreter lock
+=============================================
+
+.. index::
+ single: global interpreter lock
+ single: interpreter lock
+ single: lock, interpreter
+
+Unless on a :term:`free-threaded build` of :term:`CPython`,
+the Python interpreter is generally not thread-safe. In order to support
+multi-threaded Python programs, there's a global lock, called the :term:`global
+interpreter lock` or :term:`GIL`, that must be held by a thread before
+accessing Python objects. Without the lock, even the simplest operations
+could cause problems in a multi-threaded program: for example, when
+two threads simultaneously increment the reference count of the same object, the
+reference count could end up being incremented only once instead of twice.
+
+As such, only a thread that holds the GIL may operate on Python objects or
+invoke Python's C API.
+
+.. index:: single: setswitchinterval (in module sys)
+
+In order to emulate concurrency, the interpreter regularly tries to switch
+threads between bytecode instructions (see :func:`sys.setswitchinterval`).
+This is why locks are also necessary for thread-safety in pure-Python code.
+
+Additionally, the global interpreter lock is released around blocking I/O
+operations, such as reading or writing to a file. From the C API, this is done
+by :ref:`detaching the thread state `.
+
+
+.. index::
+ single: PyThreadState (C type)
+
+The Python interpreter keeps some thread-local information inside
+a data structure called :c:type:`PyThreadState`, known as a :term:`thread state`.
+Each thread has a thread-local pointer to a :c:type:`PyThreadState`; a thread state
+referenced by this pointer is considered to be :term:`attached `.
+
+A thread can only have one :term:`attached thread state` at a time. An attached
+thread state is typically analogous with holding the GIL, except on
+free-threaded builds. On builds with the GIL enabled, attaching a thread state
+will block until the GIL can be acquired. However, even on builds with the GIL
+disabled, it is still required to have an attached thread state, as the interpreter
+needs to keep track of which threads may access Python objects.
+
+.. note::
+
+ Even on the free-threaded build, attaching a thread state may block, as the
+ GIL can be re-enabled or threads might be temporarily suspended (such as during
+ a garbage collection).
+
+Generally, there will always be an attached thread state when using Python's
+C API, including during embedding and when implementing methods, so it's uncommon
+to need to set up a thread state on your own. Only in some specific cases, such
+as in a :c:macro:`Py_BEGIN_ALLOW_THREADS` block or in a fresh thread, will the
+thread not have an attached thread state.
+If uncertain, check if :c:func:`PyThreadState_GetUnchecked` returns ``NULL``.
+
+If it turns out that you do need to create a thread state, call :c:func:`PyThreadState_New`
+followed by :c:func:`PyThreadState_Swap`, or use the dangerous
+:c:func:`PyGILState_Ensure` function.
+
+
+.. _detaching-thread-state:
+
+Detaching the thread state from extension code
+----------------------------------------------
+
+Most extension code manipulating the :term:`thread state` has the following simple
+structure::
+
+ Save the thread state in a local variable.
+ ... Do some blocking I/O operation ...
+ Restore the thread state from the local variable.
+
+This is so common that a pair of macros exists to simplify it::
+
+ Py_BEGIN_ALLOW_THREADS
+ ... Do some blocking I/O operation ...
+ Py_END_ALLOW_THREADS
+
+.. index::
+ single: Py_BEGIN_ALLOW_THREADS (C macro)
+ single: Py_END_ALLOW_THREADS (C macro)
+
+The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
+hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the
+block.
+
+The block above expands to the following code::
+
+ PyThreadState *_save;
+
+ _save = PyEval_SaveThread();
+ ... Do some blocking I/O operation ...
+ PyEval_RestoreThread(_save);
+
+.. index::
+ single: PyEval_RestoreThread (C function)
+ single: PyEval_SaveThread (C function)
+
+Here is how these functions work:
+
+The attached thread state implies that the GIL is held for the interpreter.
+To detach it, :c:func:`PyEval_SaveThread` is called and the result is stored
+in a local variable.
+
+By detaching the thread state, the GIL is released, which allows other threads
+to attach to the interpreter and execute while the current thread performs
+blocking I/O. When the I/O operation is complete, the old thread state is
+reattached by calling :c:func:`PyEval_RestoreThread`, which will wait until
+the GIL can be acquired.
+
+.. note::
+ Performing blocking I/O is the most common use case for detaching
+ the thread state, but it is also useful to call it over long-running
+ native code that doesn't need access to Python objects or Python's C API.
+ For example, the standard :mod:`zlib` and :mod:`hashlib` modules detach the
+ :term:`thread state ` when compressing or hashing
+ data.
+
+On a :term:`free-threaded build`, the :term:`GIL` is usually out of the question,
+but **detaching the thread state is still required**, because the interpreter
+periodically needs to block all threads to get a consistent view of Python objects
+without the risk of race conditions.
+For example, CPython currently suspends all threads for a short period of time
+while running the garbage collector.
+
+.. warning::
+
+ Detaching the thread state can lead to unexpected behavior during interpreter
+ finalization. See :ref:`cautions-regarding-runtime-finalization` for more
+ details.
+
+
+APIs
+^^^^
+
+The following macros are normally used without a trailing semicolon; look for
+example usage in the Python source distribution.
+
+.. note::
+
+ These macros are still necessary on the :term:`free-threaded build` to prevent
+ deadlocks.
+
+.. c:macro:: Py_BEGIN_ALLOW_THREADS
+
+ This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
+ Note that it contains an opening brace; it must be matched with a following
+ :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this
+ macro.
+
+
+.. c:macro:: Py_END_ALLOW_THREADS
+
+ This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
+ a closing brace; it must be matched with an earlier
+ :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of
+ this macro.
+
+
+.. c:macro:: Py_BLOCK_THREADS
+
+ This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
+ :c:macro:`Py_END_ALLOW_THREADS` without the closing brace.
+
+
+.. c:macro:: Py_UNBLOCK_THREADS
+
+ This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
+ :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
+ declaration.
+
+
+Non-Python created threads
+--------------------------
+
+When threads are created using the dedicated Python APIs (such as the
+:mod:`threading` module), a thread state is automatically associated with them,
+However, when a thread is created from native code (for example, by a
+third-party library with its own thread management), it doesn't hold an
+attached thread state.
+
+If you need to call Python code from these threads (often this will be part
+of a callback API provided by the aforementioned third-party library),
+you must first register these threads with the interpreter by
+creating a new thread state and attaching it.
+
+The most robust way to do this is through :c:func:`PyThreadState_New` followed
+by :c:func:`PyThreadState_Swap`.
+
+.. note::
+ ``PyThreadState_New`` requires an argument pointing to the desired
+ interpreter; such a pointer can be acquired via a call to
+ :c:func:`PyInterpreterState_Get` from the code where the thread was
+ created.
+
+For example::
+
+ /* The return value of PyInterpreterState_Get() from the
+ function that created this thread. */
+ PyInterpreterState *interp = thread_data->interp;
+
+ /* Create a new thread state for the interpreter. It does not start out
+ attached. */
+ PyThreadState *tstate = PyThreadState_New(interp);
+
+ /* Attach the thread state, which will acquire the GIL. */
+ PyThreadState_Swap(tstate);
+
+ /* Perform Python actions here. */
+ result = CallSomeFunction();
+ /* evaluate result or handle exception */
+
+ /* Destroy the thread state. No Python API allowed beyond this point. */
+ PyThreadState_Clear(tstate);
+ PyThreadState_DeleteCurrent();
+
+.. warning::
+
+ If the interpreter finalized before ``PyThreadState_Swap`` was called, then
+ ``interp`` will be a dangling pointer!
+
+.. _gilstate:
+
+Legacy API
+----------
+
+Another common pattern to call Python code from a non-Python thread is to use
+:c:func:`PyGILState_Ensure` followed by a call to :c:func:`PyGILState_Release`.
+
+These functions do not work well when multiple interpreters exist in the Python
+process. If no Python interpreter has ever been used in the current thread (which
+is common for threads created outside Python), ``PyGILState_Ensure`` will create
+and attach a thread state for the "main" interpreter (the first interpreter in
+the Python process).
+
+Additionally, these functions have thread-safety issues during interpreter
+finalization. Using ``PyGILState_Ensure`` during finalization will likely
+crash the process.
+
+Usage of these functions look like such::
+
+ PyGILState_STATE gstate;
+ gstate = PyGILState_Ensure();
+
+ /* Perform Python actions here. */
+ result = CallSomeFunction();
+ /* evaluate result or handle exception */
+
+ /* Release the thread. No Python API allowed beyond this point. */
+ PyGILState_Release(gstate);
+
+
+.. _fork-and-threads:
+
+Cautions about fork()
+---------------------
+
+Another important thing to note about threads is their behaviour in the face
+of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a
+process forks only the thread that issued the fork will exist. This has a
+concrete impact both on how locks must be handled and on all stored state
+in CPython's runtime.
+
+The fact that only the "current" thread remains
+means any locks held by other threads will never be released. Python solves
+this for :func:`os.fork` by acquiring the locks it uses internally before
+the fork, and releasing them afterwards. In addition, it resets any
+:ref:`lock-objects` in the child. When extending or embedding Python, there
+is no way to inform Python of additional (non-Python) locks that need to be
+acquired before or reset after a fork. OS facilities such as
+:c:func:`!pthread_atfork` would need to be used to accomplish the same thing.
+Additionally, when extending or embedding Python, calling :c:func:`fork`
+directly rather than through :func:`os.fork` (and returning to or calling
+into Python) may result in a deadlock by one of Python's internal locks
+being held by a thread that is defunct after the fork.
+:c:func:`PyOS_AfterFork_Child` tries to reset the necessary locks, but is not
+always able to.
+
+The fact that all other threads go away also means that CPython's
+runtime state there must be cleaned up properly, which :func:`os.fork`
+does. This means finalizing all other :c:type:`PyThreadState` objects
+belonging to the current interpreter and all other
+:c:type:`PyInterpreterState` objects. Due to this and the special
+nature of the :ref:`"main" interpreter `,
+:c:func:`fork` should only be called in that interpreter's "main"
+thread, where the CPython global runtime was originally initialized.
+The only exception is if :c:func:`exec` will be called immediately
+after.
+
+
+High-level APIs
+---------------
+
+These are the most commonly used types and functions when writing multi-threaded
+C extensions.
+
+
+.. c:type:: PyThreadState
+
+ This data structure represents the state of a single thread. The only public
+ data member is:
+
+ .. c:member:: PyInterpreterState *interp
+
+ This thread's interpreter state.
+
+
+.. c:function:: void PyEval_InitThreads()
+
+ .. index::
+ single: PyEval_AcquireThread()
+ single: PyEval_ReleaseThread()
+ single: PyEval_SaveThread()
+ single: PyEval_RestoreThread()
+
+ Deprecated function which does nothing.
+
+ In Python 3.6 and older, this function created the GIL if it didn't exist.
+
+ .. versionchanged:: 3.9
+ The function now does nothing.
+
+ .. versionchanged:: 3.7
+ This function is now called by :c:func:`Py_Initialize()`, so you don't
+ have to call it yourself anymore.
+
+ .. versionchanged:: 3.2
+ This function cannot be called before :c:func:`Py_Initialize()` anymore.
+
+ .. deprecated:: 3.9
+
+ .. index:: pair: module; _thread
+
+
+.. c:function:: PyThreadState* PyEval_SaveThread()
+
+ Detach the :term:`attached thread state` and return it.
+ The thread will have no :term:`thread state` upon returning.
+
+
+.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate)
+
+ Set the :term:`attached thread state` to *tstate*.
+ The passed :term:`thread state` **should not** be :term:`attached `,
+ otherwise deadlock ensues. *tstate* will be attached upon returning.
+
+ .. note::
+ Calling this function from a thread when the runtime is finalizing will
+ hang the thread until the program exits, even if the thread was not
+ created by Python. Refer to
+ :ref:`cautions-regarding-runtime-finalization` for more details.
+
+ .. versionchanged:: 3.14
+ Hangs the current thread, rather than terminating it, if called while the
+ interpreter is finalizing.
+
+.. c:function:: PyThreadState* PyThreadState_Get()
+
+ Return the :term:`attached thread state`. If the thread has no attached
+ thread state, (such as when inside of :c:macro:`Py_BEGIN_ALLOW_THREADS`
+ block), then this issues a fatal error (so that the caller needn't check
+ for ``NULL``).
+
+ See also :c:func:`PyThreadState_GetUnchecked`.
+
+.. c:function:: PyThreadState* PyThreadState_GetUnchecked()
+
+ Similar to :c:func:`PyThreadState_Get`, but don't kill the process with a
+ fatal error if it is NULL. The caller is responsible to check if the result
+ is NULL.
+
+ .. versionadded:: 3.13
+ In Python 3.5 to 3.12, the function was private and known as
+ ``_PyThreadState_UncheckedGet()``.
+
+
+.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
+
+ Set the :term:`attached thread state` to *tstate*, and return the
+ :term:`thread state` that was attached prior to calling.
+
+ This function is safe to call without an :term:`attached thread state`; it
+ will simply return ``NULL`` indicating that there was no prior thread state.
+
+ .. seealso::
+ :c:func:`PyEval_ReleaseThread`
+
+ .. note::
+ Similar to :c:func:`PyGILState_Ensure`, this function will hang the
+ thread if the runtime is finalizing.
+
+
+GIL-state APIs
+--------------
+
+The following functions use thread-local storage, and are not compatible
+with sub-interpreters:
+
+.. c:type:: PyGILState_STATE
+
+ The type of the value returned by :c:func:`PyGILState_Ensure` and passed to
+ :c:func:`PyGILState_Release`.
+
+ .. c:enumerator:: PyGILState_LOCKED
+
+ The GIL was already held when :c:func:`PyGILState_Ensure` was called.
+
+ .. c:enumerator:: PyGILState_UNLOCKED
+
+ The GIL was not held when :c:func:`PyGILState_Ensure` was called.
+
+.. c:function:: PyGILState_STATE PyGILState_Ensure()
+
+ Ensure that the current thread is ready to call the Python C API regardless
+ of the current state of Python, or of the :term:`attached thread state`. This may
+ be called as many times as desired by a thread as long as each call is
+ matched with a call to :c:func:`PyGILState_Release`. In general, other
+ thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
+ :c:func:`PyGILState_Release` calls as long as the thread state is restored to
+ its previous state before the Release(). For example, normal usage of the
+ :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
+ acceptable.
+
+ The return value is an opaque "handle" to the :term:`attached thread state` when
+ :c:func:`PyGILState_Ensure` was called, and must be passed to
+ :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
+ though recursive calls are allowed, these handles *cannot* be shared - each
+ unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
+ to :c:func:`PyGILState_Release`.
+
+ When the function returns, there will be an :term:`attached thread state`
+ and the thread will be able to call arbitrary Python code. Failure is a fatal error.
+
+ .. warning::
+ Calling this function when the runtime is finalizing is unsafe. Doing
+ so will either hang the thread until the program ends, or fully crash
+ the interpreter in rare cases. Refer to
+ :ref:`cautions-regarding-runtime-finalization` for more details.
+
+ .. versionchanged:: 3.14
+ Hangs the current thread, rather than terminating it, if called while the
+ interpreter is finalizing.
+
+.. c:function:: void PyGILState_Release(PyGILState_STATE)
+
+ Release any resources previously acquired. After this call, Python's state will
+ be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
+ (but generally this state will be unknown to the caller, hence the use of the
+ GILState API).
+
+ Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
+ :c:func:`PyGILState_Release` on the same thread.
+
+.. c:function:: PyThreadState* PyGILState_GetThisThreadState()
+
+ Get the :term:`attached thread state` for this thread. May return ``NULL`` if no
+ GILState API has been used on the current thread. Note that the main thread
+ always has such a thread-state, even if no auto-thread-state call has been
+ made on the main thread. This is mainly a helper/diagnostic function.
+
+ .. note::
+ This function may return non-``NULL`` even when the :term:`thread state`
+ is detached.
+ Prefer :c:func:`PyThreadState_Get` or :c:func:`PyThreadState_GetUnchecked`
+ for most cases.
+
+ .. seealso:: :c:func:`PyThreadState_Get`
+
+.. c:function:: int PyGILState_Check()
+
+ Return ``1`` if the current thread is holding the :term:`GIL` and ``0`` otherwise.
+ This function can be called from any thread at any time.
+ Only if it has had its :term:`thread state ` initialized
+ via :c:func:`PyGILState_Ensure` will it return ``1``.
+ This is mainly a helper/diagnostic function. It can be useful
+ for example in callback contexts or memory allocation functions when
+ knowing that the :term:`GIL` is locked can allow the caller to perform sensitive
+ actions or otherwise behave differently.
+
+ .. note::
+ If the current Python process has ever created a subinterpreter, this
+ function will *always* return ``1``. Prefer :c:func:`PyThreadState_GetUnchecked`
+ for most cases.
+
+ .. versionadded:: 3.4
+
+
+Low-level APIs
+--------------
+
+.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)
+
+ Create a new thread state object belonging to the given interpreter object.
+ An :term:`attached thread state` is not needed.
+
+.. c:function:: void PyThreadState_Clear(PyThreadState *tstate)
+
+ Reset all information in a :term:`thread state` object. *tstate*
+ must be :term:`attached `
+
+ .. versionchanged:: 3.9
+ This function now calls the :c:member:`!PyThreadState.on_delete` callback.
+ Previously, that happened in :c:func:`PyThreadState_Delete`.
+
+ .. versionchanged:: 3.13
+ The :c:member:`!PyThreadState.on_delete` callback was removed.
+
+
+.. c:function:: void PyThreadState_Delete(PyThreadState *tstate)
+
+ Destroy a :term:`thread state` object. *tstate* should not
+ be :term:`attached ` to any thread.
+ *tstate* must have been reset with a previous call to
+ :c:func:`PyThreadState_Clear`.
+
+
+.. c:function:: void PyThreadState_DeleteCurrent(void)
+
+ Detach the :term:`attached thread state` (which must have been reset
+ with a previous call to :c:func:`PyThreadState_Clear`) and then destroy it.
+
+ No :term:`thread state` will be :term:`attached ` upon
+ returning.
+
+.. c:function:: PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)
+
+ Get the current frame of the Python thread state *tstate*.
+
+ Return a :term:`strong reference`. Return ``NULL`` if no frame is currently
+ executing.
+
+ See also :c:func:`PyEval_GetFrame`.
+
+ *tstate* must not be ``NULL``, and must be :term:`attached `.
+
+ .. versionadded:: 3.9
+
+
+.. c:function:: uint64_t PyThreadState_GetID(PyThreadState *tstate)
+
+ Get the unique :term:`thread state` identifier of the Python thread state *tstate*.
+
+ *tstate* must not be ``NULL``, and must be :term:`attached `.
+
+ .. versionadded:: 3.9
+
+
+.. c:function:: PyInterpreterState* PyThreadState_GetInterpreter(PyThreadState *tstate)
+
+ Get the interpreter of the Python thread state *tstate*.
+
+ *tstate* must not be ``NULL``, and must be :term:`attached `.
+
+ .. versionadded:: 3.9
+
+
+.. c:function:: void PyThreadState_EnterTracing(PyThreadState *tstate)
+
+ Suspend tracing and profiling in the Python thread state *tstate*.
+
+ Resume them using the :c:func:`PyThreadState_LeaveTracing` function.
+
+ .. versionadded:: 3.11
+
+
+.. c:function:: void PyThreadState_LeaveTracing(PyThreadState *tstate)
+
+ Resume tracing and profiling in the Python thread state *tstate* suspended
+ by the :c:func:`PyThreadState_EnterTracing` function.
+
+ See also :c:func:`PyEval_SetTrace` and :c:func:`PyEval_SetProfile`
+ functions.
+
+ .. versionadded:: 3.11
+
+
+.. c:function:: int PyUnstable_ThreadState_SetStackProtection(PyThreadState *tstate, void *stack_start_addr, size_t stack_size)
+
+ Set the stack protection start address and stack protection size
+ of a Python thread state.
+
+ On success, return ``0``.
+ On failure, set an exception and return ``-1``.
+
+ CPython implements :ref:`recursion control ` for C code by raising
+ :py:exc:`RecursionError` when it notices that the machine execution stack is close
+ to overflow. See for example the :c:func:`Py_EnterRecursiveCall` function.
+ For this, it needs to know the location of the current thread's stack, which it
+ normally gets from the operating system.
+ When the stack is changed, for example using context switching techniques like the
+ Boost library's ``boost::context``, you must call
+ :c:func:`~PyUnstable_ThreadState_SetStackProtection` to inform CPython of the change.
+
+ Call :c:func:`~PyUnstable_ThreadState_SetStackProtection` either before
+ or after changing the stack.
+ Do not call any other Python C API between the call and the stack
+ change.
+
+ See :c:func:`PyUnstable_ThreadState_ResetStackProtection` for undoing this operation.
+
+ .. versionadded:: 3.15
+
+
+.. c:function:: void PyUnstable_ThreadState_ResetStackProtection(PyThreadState *tstate)
+
+ Reset the stack protection start address and stack protection size
+ of a Python thread state to the operating system defaults.
+
+ See :c:func:`PyUnstable_ThreadState_SetStackProtection` for an explanation.
+
+ .. versionadded:: 3.15
+
+
+.. c:function:: PyObject* PyThreadState_GetDict()
+
+ Return a dictionary in which extensions can store thread-specific state
+ information. Each extension should use a unique key to use to store state in
+ the dictionary. It is okay to call this function when no :term:`thread state`
+ is :term:`attached `. If this function returns
+ ``NULL``, no exception has been raised and the caller should assume no
+ thread state is attached.
+
+
+.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)
+
+ :term:`Attach ` *tstate* to the current thread,
+ which must not be ``NULL`` or already :term:`attached `.
+
+ The calling thread must not already have an :term:`attached thread state`.
+
+ .. note::
+ Calling this function from a thread when the runtime is finalizing will
+ hang the thread until the program exits, even if the thread was not
+ created by Python. Refer to
+ :ref:`cautions-regarding-runtime-finalization` for more details.
+
+ .. versionchanged:: 3.8
+ Updated to be consistent with :c:func:`PyEval_RestoreThread`,
+ :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`,
+ and terminate the current thread if called while the interpreter is finalizing.
+
+ .. versionchanged:: 3.14
+ Hangs the current thread, rather than terminating it, if called while the
+ interpreter is finalizing.
+
+ :c:func:`PyEval_RestoreThread` is a higher-level function which is always
+ available (even when threads have not been initialized).
+
+
+.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)
+
+ Detach the :term:`attached thread state`.
+ The *tstate* argument, which must not be ``NULL``, is only used to check
+ that it represents the :term:`attached thread state` --- if it isn't, a fatal error is
+ reported.
+
+ :c:func:`PyEval_SaveThread` is a higher-level function which is always
+ available (even when threads have not been initialized).
+
+
+Asynchronous notifications
+==========================
+
+A mechanism is provided to make asynchronous notifications to the main
+interpreter thread. These notifications take the form of a function
+pointer and a void pointer argument.
+
+
+.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)
+
+ Schedule a function to be called from the main interpreter thread. On
+ success, ``0`` is returned and *func* is queued for being called in the
+ main thread. On failure, ``-1`` is returned without setting any exception.
+
+ When successfully queued, *func* will be *eventually* called from the
+ main interpreter thread with the argument *arg*. It will be called
+ asynchronously with respect to normally running Python code, but with
+ both these conditions met:
+
+ * on a :term:`bytecode` boundary;
+ * with the main thread holding an :term:`attached thread state`
+ (*func* can therefore use the full C API).
+
+ *func* must return ``0`` on success, or ``-1`` on failure with an exception
+ set. *func* won't be interrupted to perform another asynchronous
+ notification recursively, but it can still be interrupted to switch
+ threads if the :term:`thread state ` is detached.
+
+ This function doesn't need an :term:`attached thread state`. However, to call this
+ function in a subinterpreter, the caller must have an :term:`attached thread state`.
+ Otherwise, the function *func* can be scheduled to be called from the wrong interpreter.
+
+ .. warning::
+ This is a low-level function, only useful for very special cases.
+ There is no guarantee that *func* will be called as quick as
+ possible. If the main thread is busy executing a system call,
+ *func* won't be called before the system call returns. This
+ function is generally **not** suitable for calling Python code from
+ arbitrary C threads. Instead, use the :ref:`PyGILState API`.
+
+ .. versionadded:: 3.1
+
+ .. versionchanged:: 3.9
+ If this function is called in a subinterpreter, the function *func* is
+ now scheduled to be called from the subinterpreter, rather than being
+ called from the main interpreter. Each subinterpreter now has its own
+ list of scheduled calls.
+
+ .. versionchanged:: 3.12
+ This function now always schedules *func* to be run in the main
+ interpreter.
+
+
+.. c:function:: int Py_MakePendingCalls(void)
+
+ Execute all pending calls. This is usually executed automatically by the
+ interpreter.
+
+ This function returns ``0`` on success, and returns ``-1`` with an exception
+ set on failure.
+
+ If this is not called in the main thread of the main
+ interpreter, this function does nothing and returns ``0``.
+ The caller must hold an :term:`attached thread state`.
+
+ .. versionadded:: 3.1
+
+ .. versionchanged:: 3.12
+ This function only runs pending calls in the main interpreter.
+
+
+.. c:function:: int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
+
+ Schedule an exception to be raised asynchronously in a thread.
+ If the thread has a previously scheduled exception, it is overwritten.
+
+ The *id* argument is the thread id of the target thread, as returned by
+ :c:func:`PyThread_get_thread_ident`.
+ *exc* is the class of the exception to be raised, or ``NULL`` to clear
+ the pending exception (if any).
+
+ Return the number of affected thread states.
+ This is normally ``1`` if *id* is found, even when no change was
+ made (the given *exc* was already pending, or *exc* is ``NULL`` but
+ no exception is pending).
+ If the thread id isn't found, return ``0``. This raises no exceptions.
+
+ To prevent naive misuse, you must write your own C extension to call this.
+ This function must be called with an :term:`attached thread state`.
+ This function does not steal any references to *exc*.
+ This function does not necessarily interrupt system calls such as
+ :py:func:`~time.sleep`.
+
+ .. versionchanged:: 3.7
+ The type of the *id* parameter changed from :c:expr:`long` to
+ :c:expr:`unsigned long`.
+
+
+Operating system thread APIs
+============================
+
+.. c:macro:: PYTHREAD_INVALID_THREAD_ID
+
+ Sentinel value for an invalid thread ID.
+
+ This is currently equivalent to ``(unsigned long)-1``.
+
+
+.. c:function:: unsigned long PyThread_start_new_thread(void (*func)(void *), void *arg)
+
+ Start function *func* in a new thread with argument *arg*.
+ The resulting thread is not intended to be joined.
+
+ *func* must not be ``NULL``, but *arg* may be ``NULL``.
+
+ On success, this function returns the identifier of the new thread; on failure,
+ this returns :c:macro:`PYTHREAD_INVALID_THREAD_ID`.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: unsigned long PyThread_get_thread_ident(void)
+
+ Return the identifier of the current thread, which will never be zero.
+
+ This function cannot fail, and the caller does not need to hold an
+ :term:`attached thread state`.
+
+ .. seealso::
+ :py:func:`threading.get_ident` and :py:attr:`threading.Thread.ident`
+ expose this identifier to Python.
+
+
+.. c:function:: PyObject *PyThread_GetInfo(void)
+
+ Get general information about the current thread in the form of a
+ :ref:`struct sequence ` object. This information is
+ accessible as :py:attr:`sys.thread_info` in Python.
+
+ On success, this returns a new :term:`strong reference` to the thread
+ information; on failure, this returns ``NULL`` with an exception set.
+
+ The caller must hold an :term:`attached thread state`.
+
+
+.. c:macro:: PY_HAVE_THREAD_NATIVE_ID
+
+ This macro is defined when the system supports native thread IDs.
+
+
+.. c:function:: unsigned long PyThread_get_thread_native_id(void)
+
+ Get the native identifier of the current thread as it was assigned by the operating
+ system's kernel, which will never be less than zero.
+
+ This function is only available when :c:macro:`PY_HAVE_THREAD_NATIVE_ID` is
+ defined.
+
+ This function cannot fail, and the caller does not need to hold an
+ :term:`attached thread state`.
+
+ .. seealso::
+ :py:func:`threading.get_native_id`
+
+
+.. c:function:: void PyThread_exit_thread(void)
+
+ Terminate the current thread. This function is generally considered unsafe
+ and should be avoided. It is kept solely for backwards compatibility.
+
+ This function is only safe to call if all functions in the full call
+ stack are written to safely allow it.
+
+ .. warning::
+
+ If the current system uses POSIX threads (also known as "pthreads"),
+ this calls :manpage:`pthread_exit(3)`, which attempts to unwind the stack
+ and call C++ destructors on some libc implementations. However, if a
+ ``noexcept`` function is reached, it may terminate the process.
+ Other systems, such as macOS, do unwinding.
+
+ On Windows, this function calls ``_endthreadex()``, which kills the thread
+ without calling C++ destructors.
+
+ In any case, there is a risk of corruption on the thread's stack.
+
+ .. deprecated:: 3.14
+
+
+.. c:function:: void PyThread_init_thread(void)
+
+ Initialize ``PyThread*`` APIs. Python executes this function automatically,
+ so there's little need to call it from an extension module.
+
+
+.. c:function:: int PyThread_set_stacksize(size_t size)
+
+ Set the stack size of the current thread to *size* bytes.
+
+ This function returns ``0`` on success, ``-1`` if *size* is invalid, or
+ ``-2`` if the system does not support changing the stack size. This function
+ does not set exceptions.
+
+ The caller does not need to hold an :term:`attached thread state`.
+
+
+.. c:function:: size_t PyThread_get_stacksize(void)
+
+ Return the stack size of the current thread in bytes, or ``0`` if the system's
+ default stack size is in use.
+
+ The caller does not need to hold an :term:`attached thread state`.
diff --git a/Doc/c-api/tls.rst b/Doc/c-api/tls.rst
new file mode 100644
index 00000000000000..93ac5557141e25
--- /dev/null
+++ b/Doc/c-api/tls.rst
@@ -0,0 +1,155 @@
+.. highlight:: c
+
+.. _thread-local-storage:
+
+Thread-local storage support
+============================
+
+The Python interpreter provides low-level support for thread-local storage
+(TLS) which wraps the underlying native TLS implementation to support the
+Python-level thread-local storage API (:class:`threading.local`). The
+CPython C level APIs are similar to those offered by pthreads and Windows:
+use a thread key and functions to associate a :c:expr:`void*` value per
+thread.
+
+A :term:`thread state` does *not* need to be :term:`attached `
+when calling these functions; they supply their own locking.
+
+Note that :file:`Python.h` does not include the declaration of the TLS APIs,
+you need to include :file:`pythread.h` to use thread-local storage.
+
+.. note::
+ None of these API functions handle memory management on behalf of the
+ :c:expr:`void*` values. You need to allocate and deallocate them yourself.
+ If the :c:expr:`void*` values happen to be :c:expr:`PyObject*`, these
+ functions don't do refcount operations on them either.
+
+.. _thread-specific-storage-api:
+
+Thread-specific storage API
+---------------------------
+
+The thread-specific storage (TSS) API was introduced to supersede the use of the existing TLS API within the
+CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of
+:c:expr:`int` to represent thread keys.
+
+.. versionadded:: 3.7
+
+.. seealso:: "A New C-API for Thread-Local Storage in CPython" (:pep:`539`)
+
+
+.. c:type:: Py_tss_t
+
+ This data structure represents the state of a thread key, the definition of
+ which may depend on the underlying TLS implementation, and it has an
+ internal field representing the key's initialization state. There are no
+ public members in this structure.
+
+ When :ref:`Py_LIMITED_API ` is not defined, static allocation of
+ this type by :c:macro:`Py_tss_NEEDS_INIT` is allowed.
+
+
+.. c:macro:: Py_tss_NEEDS_INIT
+
+ This macro expands to the initializer for :c:type:`Py_tss_t` variables.
+ Note that this macro won't be defined with :ref:`Py_LIMITED_API `.
+
+
+Dynamic allocation
+------------------
+
+Dynamic allocation of the :c:type:`Py_tss_t`, required in extension modules
+built with :ref:`Py_LIMITED_API `, where static allocation of this type
+is not possible due to its implementation being opaque at build time.
+
+
+.. c:function:: Py_tss_t* PyThread_tss_alloc()
+
+ Return a value which is the same state as a value initialized with
+ :c:macro:`Py_tss_NEEDS_INIT`, or ``NULL`` in the case of dynamic allocation
+ failure.
+
+
+.. c:function:: void PyThread_tss_free(Py_tss_t *key)
+
+ Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after
+ first calling :c:func:`PyThread_tss_delete` to ensure any associated
+ thread locals have been unassigned. This is a no-op if the *key*
+ argument is ``NULL``.
+
+ .. note::
+ A freed key becomes a dangling pointer. You should reset the key to
+ ``NULL``.
+
+
+Methods
+-------
+
+The parameter *key* of these functions must not be ``NULL``. Moreover, the
+behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are
+undefined if the given :c:type:`Py_tss_t` has not been initialized by
+:c:func:`PyThread_tss_create`.
+
+
+.. c:function:: int PyThread_tss_is_created(Py_tss_t *key)
+
+ Return a non-zero value if the given :c:type:`Py_tss_t` has been initialized
+ by :c:func:`PyThread_tss_create`.
+
+
+.. c:function:: int PyThread_tss_create(Py_tss_t *key)
+
+ Return a zero value on successful initialization of a TSS key. The behavior
+ is undefined if the value pointed to by the *key* argument is not
+ initialized by :c:macro:`Py_tss_NEEDS_INIT`. This function can be called
+ repeatedly on the same key -- calling it on an already initialized key is a
+ no-op and immediately returns success.
+
+
+.. c:function:: void PyThread_tss_delete(Py_tss_t *key)
+
+ Destroy a TSS key to forget the values associated with the key across all
+ threads, and change the key's initialization state to uninitialized. A
+ destroyed key is able to be initialized again by
+ :c:func:`PyThread_tss_create`. This function can be called repeatedly on
+ the same key -- calling it on an already destroyed key is a no-op.
+
+
+.. c:function:: int PyThread_tss_set(Py_tss_t *key, void *value)
+
+ Return a zero value to indicate successfully associating a :c:expr:`void*`
+ value with a TSS key in the current thread. Each thread has a distinct
+ mapping of the key to a :c:expr:`void*` value.
+
+
+.. c:function:: void* PyThread_tss_get(Py_tss_t *key)
+
+ Return the :c:expr:`void*` value associated with a TSS key in the current
+ thread. This returns ``NULL`` if no value is associated with the key in the
+ current thread.
+
+
+.. _thread-local-storage-api:
+
+Legacy APIs
+-----------
+
+.. deprecated:: 3.7
+ This API is superseded by the
+ :ref:`thread-specific storage (TSS) API `.
+
+.. note::
+ This version of the API does not support platforms where the native TLS key
+ is defined in a way that cannot be safely cast to ``int``. On such platforms,
+ :c:func:`PyThread_create_key` will return immediately with a failure status,
+ and the other TLS functions will all be no-ops on such platforms.
+
+Due to the compatibility problem noted above, this version of the API should not
+be used in new code.
+
+.. c:function:: int PyThread_create_key()
+.. c:function:: void PyThread_delete_key(int key)
+.. c:function:: int PyThread_set_key_value(int key, void *value)
+.. c:function:: void* PyThread_get_key_value(int key)
+.. c:function:: void PyThread_delete_key_value(int key)
+.. c:function:: void PyThread_ReInitTLS()
diff --git a/Doc/c-api/type.rst b/Doc/c-api/type.rst
index 8cadf26cee3027..c9bb5c3f09ac18 100644
--- a/Doc/c-api/type.rst
+++ b/Doc/c-api/type.rst
@@ -274,6 +274,10 @@ Type Objects
Return the module object associated with the given type when the type was
created using :c:func:`PyType_FromModuleAndSpec`.
+ The returned reference is :term:`borrowed ` from *type*,
+ and will be valid as long as you hold a reference to *type*.
+ Do not release it with :c:func:`Py_DECREF` or similar.
+
If no module is associated with the given type, sets :py:class:`TypeError`
and returns ``NULL``.
diff --git a/Doc/c-api/typeobj.rst b/Doc/c-api/typeobj.rst
index a33da367e6071f..87b488912653b9 100644
--- a/Doc/c-api/typeobj.rst
+++ b/Doc/c-api/typeobj.rst
@@ -1499,6 +1499,52 @@ and :c:data:`PyType_Type` effectively act as defaults.)
It will be removed in a future version of CPython
+ .. c:macro:: Py_TPFLAGS_HAVE_VERSION_TAG
+
+ This is a :term:`soft deprecated` macro that does nothing.
+ Historically, this would indicate that the
+ :c:member:`~PyTypeObject.tp_version_tag` field was available and
+ initialized.
+
+
+ .. c:macro:: Py_TPFLAGS_INLINE_VALUES
+
+ This bit indicates that instances of this type will have an "inline values"
+ array (containing the object's attributes) placed directly after the end
+ of the object.
+
+ This requires that :c:macro:`Py_TPFLAGS_HAVE_GC` is set.
+
+ **Inheritance:**
+
+ This flag is not inherited.
+
+ .. versionadded:: 3.13
+
+
+ .. c:macro:: Py_TPFLAGS_IS_ABSTRACT
+
+ This bit indicates that this is an abstract type and therefore cannot
+ be instantiated.
+
+ **Inheritance:**
+
+ This flag is not inherited.
+
+ .. seealso::
+ :mod:`abc`
+
+
+ .. c:macro:: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION
+
+ Internal. Do not set or unset this flag.
+ Historically, this was a reserved flag for use in Stackless Python.
+
+ .. warning::
+ This flag is present in header files, but is not be used.
+ This may be removed in a future version of CPython.
+
+
.. c:member:: const char* PyTypeObject.tp_doc
.. corresponding-type-slot:: Py_tp_doc
@@ -2632,9 +2678,6 @@ This is done by filling a :c:type:`PyType_Spec` structure and calling
Number Object Structures
------------------------
-.. sectionauthor:: Amaury Forgeot d'Arc
-
-
.. c:type:: PyNumberMethods
This structure holds pointers to the functions which an object uses to
@@ -2852,9 +2895,6 @@ Number Object Structures
Mapping Object Structures
-------------------------
-.. sectionauthor:: Amaury Forgeot d'Arc
-
-
.. c:type:: PyMappingMethods
This structure holds pointers to the functions which an object uses to
@@ -2895,9 +2935,6 @@ Mapping Object Structures
Sequence Object Structures
--------------------------
-.. sectionauthor:: Amaury Forgeot d'Arc
-
-
.. c:type:: PySequenceMethods
This structure holds pointers to the functions which an object uses to
@@ -2991,10 +3028,6 @@ Sequence Object Structures
Buffer Object Structures
------------------------
-.. sectionauthor:: Greg J. Stein
-.. sectionauthor:: Benjamin Peterson
-.. sectionauthor:: Stefan Krah
-
.. c:type:: PyBufferProcs
This structure holds pointers to the functions required by the
@@ -3090,8 +3123,6 @@ Buffer Object Structures
Async Object Structures
-----------------------
-.. sectionauthor:: Yury Selivanov
-
.. versionadded:: 3.5
.. c:type:: PyAsyncMethods
diff --git a/Doc/c-api/unicode.rst b/Doc/c-api/unicode.rst
index d2b6643c700e88..4845e0f300278d 100644
--- a/Doc/c-api/unicode.rst
+++ b/Doc/c-api/unicode.rst
@@ -5,9 +5,6 @@
Unicode Objects and Codecs
--------------------------
-.. sectionauthor:: Marc-Andrรฉ Lemburg
-.. sectionauthor:: Georg Brandl
-
Unicode Objects
^^^^^^^^^^^^^^^
diff --git a/Doc/c-api/veryhigh.rst b/Doc/c-api/veryhigh.rst
index 7eb9f0b54abd4e..6256bf7a1454a9 100644
--- a/Doc/c-api/veryhigh.rst
+++ b/Doc/c-api/veryhigh.rst
@@ -191,7 +191,7 @@ the same library that the Python runtime is using.
objects *globals* and *locals* with the compiler flags specified by
*flags*. *globals* must be a dictionary; *locals* can be any object
that implements the mapping protocol. The parameter *start* specifies
- the start symbol and must one of the :ref:`available start symbols `.
+ the start symbol and must be one of the :ref:`available start symbols `.
Returns the result of executing the code as a Python object, or ``NULL`` if an
exception was raised.
diff --git a/Doc/conf.py b/Doc/conf.py
index f6efc5ff22a5e1..4ac6f6192a0806 100644
--- a/Doc/conf.py
+++ b/Doc/conf.py
@@ -33,6 +33,7 @@
'issue_role',
'lexers',
'misc_news',
+ 'profiling_trace',
'pydoc_topics',
'pyspecific',
'sphinx.ext.coverage',
@@ -42,8 +43,10 @@
# Skip if downstream redistributors haven't installed them
_OPTIONAL_EXTENSIONS = (
+ 'linklint.ext',
'notfound.extension',
'sphinxext.opengraph',
+ 'sphinxcontrib.rsvgconverter',
)
for optional_ext in _OPTIONAL_EXTENSIONS:
try:
@@ -226,10 +229,6 @@
# Temporary undocumented names.
# In future this list must be empty.
nitpick_ignore += [
- # Do not error nit-picky mode builds when _SubParsersAction.add_parser cannot
- # be resolved, as the method is currently undocumented. For context, see
- # https://github.com/python/cpython/pull/103289.
- ('py:meth', '_SubParsersAction.add_parser'),
# Attributes/methods/etc. that definitely should be documented better,
# but are deferred for now:
('py:attr', '__wrapped__'),
@@ -558,6 +557,7 @@
# mapping unique short aliases to a base URL and a prefix.
# https://www.sphinx-doc.org/en/master/usage/extensions/extlinks.html
extlinks = {
+ "oss-fuzz": ("https://issues.oss-fuzz.com/issues/%s", "#%s"),
"pypi": ("https://pypi.org/project/%s/", "%s"),
"source": (SOURCE_URI, "%s"),
}
@@ -569,6 +569,7 @@
# Relative filename of the data files
refcount_file = 'data/refcounts.dat'
stable_abi_file = 'data/stable_abi.dat'
+threadsafety_file = 'data/threadsafety.dat'
# Options for sphinxext-opengraph
# -------------------------------
diff --git a/Doc/data/refcounts.dat b/Doc/data/refcounts.dat
index 64399f6ab1ff26..01b064f3e617ff 100644
--- a/Doc/data/refcounts.dat
+++ b/Doc/data/refcounts.dat
@@ -2427,6 +2427,9 @@ PyType_GetFlags:PyTypeObject*:type:0:
PyType_GetName:PyObject*::+1:
PyType_GetName:PyTypeObject*:type:0:
+PyType_GetModule:PyObject*::0:
+PyType_GetModule:PyTypeObject*:type:0:
+
PyType_GetModuleByToken:PyObject*::+1:
PyType_GetModuleByToken:PyTypeObject*:type:0:
PyType_GetModuleByToken:PyModuleDef*:def::
diff --git a/Doc/data/threadsafety.dat b/Doc/data/threadsafety.dat
new file mode 100644
index 00000000000000..f063ca1360d5fb
--- /dev/null
+++ b/Doc/data/threadsafety.dat
@@ -0,0 +1,19 @@
+# Thread safety annotations for C API functions.
+#
+# Each line has the form:
+# function_name : level
+#
+# Where level is one of:
+# incompatible -- not safe even with external locking
+# compatible -- safe if the caller serializes all access with external locks
+# distinct -- safe on distinct objects without external synchronization
+# shared -- safe for concurrent use on the same object
+# atomic -- atomic
+#
+# Lines beginning with '#' are ignored.
+# The function name must match the C domain identifier used in the documentation.
+
+# Synchronization primitives (Doc/c-api/synchronization.rst)
+PyMutex_Lock:shared:
+PyMutex_Unlock:shared:
+PyMutex_IsLocked:atomic:
diff --git a/Doc/deprecations/c-api-pending-removal-in-3.19.rst b/Doc/deprecations/c-api-pending-removal-in-3.19.rst
new file mode 100644
index 00000000000000..ac9dcb8b424a17
--- /dev/null
+++ b/Doc/deprecations/c-api-pending-removal-in-3.19.rst
@@ -0,0 +1,4 @@
+Pending removal in Python 3.19
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+* :pep:`456` embedders support for the string hashing scheme definition.
diff --git a/Doc/deprecations/index.rst b/Doc/deprecations/index.rst
index c91c64a1092457..bb8bfb5c227c2d 100644
--- a/Doc/deprecations/index.rst
+++ b/Doc/deprecations/index.rst
@@ -20,8 +20,12 @@ C API deprecations
.. include:: c-api-pending-removal-in-3.15.rst
+.. include:: c-api-pending-removal-in-3.16.rst
+
.. include:: c-api-pending-removal-in-3.18.rst
+.. include:: c-api-pending-removal-in-3.19.rst
+
.. include:: c-api-pending-removal-in-3.20.rst
.. include:: c-api-pending-removal-in-future.rst
diff --git a/Doc/deprecations/pending-removal-in-3.15.rst b/Doc/deprecations/pending-removal-in-3.15.rst
index 00266b1725c8a1..e7f27f73664df3 100644
--- a/Doc/deprecations/pending-removal-in-3.15.rst
+++ b/Doc/deprecations/pending-removal-in-3.15.rst
@@ -54,7 +54,7 @@ Pending removal in Python 3.15
* :func:`~threading.RLock` will take no arguments in Python 3.15.
Passing any arguments has been deprecated since Python 3.14,
- as the Python version does not permit any arguments,
+ as the Python version does not permit any arguments,
but the C version allows any number of positional or keyword arguments,
ignoring every argument.
diff --git a/Doc/deprecations/pending-removal-in-3.18.rst b/Doc/deprecations/pending-removal-in-3.18.rst
index 3e799219478424..eb42fe9919eaeb 100644
--- a/Doc/deprecations/pending-removal-in-3.18.rst
+++ b/Doc/deprecations/pending-removal-in-3.18.rst
@@ -1,6 +1,9 @@
Pending removal in Python 3.18
------------------------------
+* No longer accept a boolean value when a file descriptor is expected.
+ (Contributed by Serhiy Storchaka in :gh:`82626`.)
+
* :mod:`decimal`:
* The non-standard and undocumented :class:`~decimal.Decimal` format
diff --git a/Doc/deprecations/pending-removal-in-3.20.rst b/Doc/deprecations/pending-removal-in-3.20.rst
index 4e4b2e1d5f8fff..176e8f3f9f601c 100644
--- a/Doc/deprecations/pending-removal-in-3.20.rst
+++ b/Doc/deprecations/pending-removal-in-3.20.rst
@@ -1,6 +1,13 @@
Pending removal in Python 3.20
------------------------------
+* Calling the ``__new__()`` method of :class:`struct.Struct` without the
+ *format* argument is deprecated and will be removed in Python 3.20. Calling
+ :meth:`~object.__init__` method on initialized :class:`~struct.Struct`
+ objects is deprecated and will be removed in Python 3.20.
+
+ (Contributed by Sergey B Kirpichev and Serhiy Storchaka in :gh:`143715`.)
+
* The ``__version__``, ``version`` and ``VERSION`` attributes have been
deprecated in these standard library modules and will be removed in
Python 3.20. Use :py:data:`sys.version_info` instead.
@@ -21,6 +28,7 @@ Pending removal in Python 3.20
- :mod:`re`
- :mod:`socketserver`
- :mod:`tabnanny`
+ - :mod:`tarfile`
- :mod:`tkinter.font`
- :mod:`tkinter.ttk`
- :mod:`wsgiref.simple_server`
diff --git a/Doc/deprecations/pending-removal-in-future.rst b/Doc/deprecations/pending-removal-in-future.rst
index 301867416701ea..e8306b8efee1c8 100644
--- a/Doc/deprecations/pending-removal-in-future.rst
+++ b/Doc/deprecations/pending-removal-in-future.rst
@@ -35,7 +35,6 @@ although there is currently no date scheduled for their removal.
* Support for ``__complex__()`` method returning a strict subclass of
:class:`complex`: these methods will be required to return an instance of
:class:`complex`.
- * Delegation of ``int()`` to ``__trunc__()`` method.
* Passing a complex number as the *real* or *imag* argument in the
:func:`complex` constructor is now deprecated; it should only be passed
as a single positional argument.
@@ -78,6 +77,14 @@ although there is currently no date scheduled for their removal.
* :mod:`os`: Calling :func:`os.register_at_fork` in a multi-threaded process.
+* :mod:`os.path`: :func:`os.path.commonprefix` is deprecated, use
+ :func:`os.path.commonpath` for path prefixes. The :func:`os.path.commonprefix`
+ function is being deprecated due to having a misleading name and module.
+ The function is not safe to use for path prefixes despite being included in a
+ module about path manipulation, meaning it is easy to accidentally
+ introduce path traversal vulnerabilities into Python programs by using this
+ function.
+
* :class:`!pydoc.ErrorDuringImport`: A tuple value for *exc_info* parameter is
deprecated, use an exception instance.
diff --git a/Doc/extending/extending.rst b/Doc/extending/extending.rst
index c0066d315d092b..d33cbd2813d637 100644
--- a/Doc/extending/extending.rst
+++ b/Doc/extending/extending.rst
@@ -903,9 +903,6 @@ define this symbol).
Providing a C API for an Extension Module
=========================================
-.. sectionauthor:: Konrad Hinsen
-
-
Many extension modules just provide new functions and types to be used from
Python, but sometimes the code in an extension module can be useful for other
extension modules. For example, an extension module could implement a type
diff --git a/Doc/extending/newtypes_tutorial.rst b/Doc/extending/newtypes_tutorial.rst
index 3bbee33bd50698..9f3cd1d6f4cf33 100644
--- a/Doc/extending/newtypes_tutorial.rst
+++ b/Doc/extending/newtypes_tutorial.rst
@@ -6,11 +6,6 @@
Defining Extension Types: Tutorial
**********************************
-.. sectionauthor:: Michael Hudson
-.. sectionauthor:: Dave Kuhlman
-.. sectionauthor:: Jim Fulton
-
-
Python allows the writer of a C extension module to define new types that
can be manipulated from Python code, much like the built-in :class:`str`
and :class:`list` types. The code for all extension types follows a
diff --git a/Doc/extending/windows.rst b/Doc/extending/windows.rst
index a97c6182553c30..cd81b443603d17 100644
--- a/Doc/extending/windows.rst
+++ b/Doc/extending/windows.rst
@@ -47,9 +47,6 @@ things manually, it may be instructive to study the project file for the
Differences Between Unix and Windows
====================================
-.. sectionauthor:: Chris Phoenix
-
-
Unix and Windows use completely different paradigms for run-time loading of
code. Before you try to build a module that can be dynamically loaded, be aware
of how your system works.
@@ -109,9 +106,6 @@ separate copy.
Using DLLs in Practice
======================
-.. sectionauthor:: Chris Phoenix
-
-
Windows Python is built in Microsoft Visual C++; using other compilers may or
may not work. The rest of this section is MSVC++ specific.
diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst
index 138a5ca7a7516f..8bd2bc99d74b83 100644
--- a/Doc/faq/programming.rst
+++ b/Doc/faq/programming.rst
@@ -8,11 +8,11 @@ Programming FAQ
.. contents::
-General Questions
+General questions
=================
-Is there a source code level debugger with breakpoints, single-stepping, etc.?
-------------------------------------------------------------------------------
+Is there a source code-level debugger with breakpoints and single-stepping?
+---------------------------------------------------------------------------
Yes.
@@ -25,8 +25,7 @@ Reference Manual `. You can also write your own debugger by using the code
for pdb as an example.
The IDLE interactive development environment, which is part of the standard
-Python distribution (normally available as
-`Tools/scripts/idle3 `_),
+Python distribution (normally available as :mod:`idlelib`),
includes a graphical debugger.
PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
@@ -48,7 +47,6 @@ There are a number of commercial Python IDEs that include graphical debuggers.
They include:
* `Wing IDE `_
-* `Komodo IDE `_
* `PyCharm `_
@@ -57,13 +55,15 @@ Are there tools to help find bugs or perform static analysis?
Yes.
-`Pylint `_ and
-`Pyflakes `_ do basic checking that will
+`Ruff `__,
+`Pylint `__ and
+`Pyflakes `__ do basic checking that will
help you catch bugs sooner.
-Static type checkers such as `Mypy `_,
-`Pyre `_, and
-`Pytype `_ can check type hints in Python
+Static type checkers such as `mypy `__,
+`ty `__,
+`Pyrefly `__, and
+`pytype `__ can check type hints in Python
source code.
@@ -79,7 +79,7 @@ set of modules required by a program and bind these modules together with a
Python binary to produce a single executable.
One is to use the freeze tool, which is included in the Python source tree as
-`Tools/freeze `_.
+:source:`Tools/freeze`.
It converts Python byte code to C arrays; with a C compiler you can
embed all your modules into a new program, which is then linked with the
standard Python modules.
@@ -103,6 +103,7 @@ executables:
* `py2app `_ (macOS only)
* `py2exe `_ (Windows only)
+
Are there coding standards or a style guide for Python programs?
----------------------------------------------------------------
@@ -110,7 +111,7 @@ Yes. The coding style required for standard library modules is documented as
:pep:`8`.
-Core Language
+Core language
=============
.. _faq-unboundlocalerror:
@@ -143,7 +144,7 @@ results in an :exc:`!UnboundLocalError`:
>>> foo()
Traceback (most recent call last):
...
- UnboundLocalError: local variable 'x' referenced before assignment
+ UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
This is because when you make an assignment to a variable in a scope, that
variable becomes local to that scope and shadows any similarly named variable
@@ -208,7 +209,7 @@ Why do lambdas defined in a loop with different values all return the same resul
----------------------------------------------------------------------------------
Assume you use a for loop to define a few different lambdas (or even plain
-functions), e.g.::
+functions), for example::
>>> squares = []
>>> for x in range(5):
@@ -227,7 +228,7 @@ they all return ``16``::
This happens because ``x`` is not local to the lambdas, but is defined in
the outer scope, and it is accessed when the lambda is called --- not when it
is defined. At the end of the loop, the value of ``x`` is ``4``, so all the
-functions now return ``4**2``, i.e. ``16``. You can also verify this by
+functions now return ``4**2``, that is ``16``. You can also verify this by
changing the value of ``x`` and see how the results of the lambdas change::
>>> x = 8
@@ -298,9 +299,9 @@ using multiple imports per line uses less screen space.
It's good practice if you import modules in the following order:
-1. standard library modules -- e.g. :mod:`sys`, :mod:`os`, :mod:`argparse`, :mod:`re`
+1. standard library modules -- such as :mod:`sys`, :mod:`os`, :mod:`argparse`, :mod:`re`
2. third-party library modules (anything installed in Python's site-packages
- directory) -- e.g. :mod:`!dateutil`, :mod:`!requests`, :mod:`!PIL.Image`
+ directory) -- such as :pypi:`dateutil`, :pypi:`requests`, :pypi:`tzdata`
3. locally developed modules
It is sometimes necessary to move imports to a function or class to avoid
@@ -494,11 +495,11 @@ new objects).
In other words:
-* If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`,
- etc.), we can use some specific operations to mutate it and all the variables
+* If we have a mutable object (such as :class:`list`, :class:`dict`, :class:`set`),
+ we can use some specific operations to mutate it and all the variables
that refer to it will see the change.
-* If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`,
- etc.), all the variables that refer to it will always see the same value,
+* If we have an immutable object (such as :class:`str`, :class:`int`, :class:`tuple`),
+ all the variables that refer to it will always see the same value,
but operations that transform that value into a new value always return a new
object.
@@ -511,7 +512,7 @@ How do I write a function with output parameters (call by reference)?
Remember that arguments are passed by assignment in Python. Since assignment
just creates references to objects, there's no alias between an argument name in
-the caller and callee, and so no call-by-reference per se. You can achieve the
+the caller and callee, and consequently no call-by-reference. You can achieve the
desired effect in a number of ways.
1) By returning a tuple of the results::
@@ -714,8 +715,8 @@ not::
"a" in ("b", "a")
-The same is true of the various assignment operators (``=``, ``+=`` etc). They
-are not truly operators but syntactic delimiters in assignment statements.
+The same is true of the various assignment operators (``=``, ``+=``, and so on).
+They are not truly operators but syntactic delimiters in assignment statements.
Is there an equivalent of C's "?:" ternary operator?
@@ -868,9 +869,9 @@ with either a space or parentheses.
How do I convert a string to a number?
--------------------------------------
-For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
+For integers, use the built-in :func:`int` type constructor, for example, ``int('144')
== 144``. Similarly, :func:`float` converts to a floating-point number,
-e.g. ``float('144') == 144.0``.
+for example, ``float('144') == 144.0``.
By default, these interpret the number as decimal, so that ``int('0144') ==
144`` holds true, and ``int('0x144')`` raises :exc:`ValueError`. ``int(string,
@@ -887,18 +888,18 @@ unwanted side effects. For example, someone could pass
directory.
:func:`eval` also has the effect of interpreting numbers as Python expressions,
-so that e.g. ``eval('09')`` gives a syntax error because Python does not allow
+so that, for example, ``eval('09')`` gives a syntax error because Python does not allow
leading '0' in a decimal number (except '0').
How do I convert a number to a string?
--------------------------------------
-To convert, e.g., the number ``144`` to the string ``'144'``, use the built-in type
+For example, to convert the number ``144`` to the string ``'144'``, use the built-in type
constructor :func:`str`. If you want a hexadecimal or octal representation, use
the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
-the :ref:`f-strings` and :ref:`formatstrings` sections,
-e.g. ``"{:04d}".format(144)`` yields
+the :ref:`f-strings` and :ref:`formatstrings` sections.
+For example, ``"{:04d}".format(144)`` yields
``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.
@@ -908,7 +909,7 @@ How do I modify a string in place?
You can't, because strings are immutable. In most situations, you should
simply construct a new string from the various parts you want to assemble
it from. However, if you need an object with the ability to modify in-place
-unicode data, try using an :class:`io.StringIO` object or the :mod:`array`
+Unicode data, try using an :class:`io.StringIO` object or the :mod:`array`
module::
>>> import io
@@ -1066,13 +1067,14 @@ the raw string::
Also see the specification in the :ref:`language reference `.
+
Performance
===========
My program is too slow. How do I speed it up?
---------------------------------------------
-That's a tough one, in general. First, here are a list of things to
+That's a tough one, in general. First, here is list of things to
remember before diving further:
* Performance characteristics vary across Python implementations. This FAQ
@@ -1125,6 +1127,7 @@ yourself.
The wiki page devoted to `performance tips
`_.
+
.. _efficient_string_concatenation:
What is the most efficient way to concatenate many strings together?
@@ -1143,7 +1146,7 @@ them into a list and call :meth:`str.join` at the end::
chunks.append(s)
result = ''.join(chunks)
-(another reasonably efficient idiom is to use :class:`io.StringIO`)
+(Another reasonably efficient idiom is to use :class:`io.StringIO`.)
To accumulate many :class:`bytes` objects, the recommended idiom is to extend
a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
@@ -1153,7 +1156,7 @@ a :class:`bytearray` object using in-place concatenation (the ``+=`` operator)::
result += b
-Sequences (Tuples/Lists)
+Sequences (tuples/lists)
========================
How do I convert between tuples and lists?
@@ -1217,8 +1220,8 @@ list, deleting duplicates as you go::
else:
last = mylist[i]
-If all elements of the list may be used as set keys (i.e. they are all
-:term:`hashable`) this is often faster ::
+If all elements of the list may be used as set keys (that is, they are all
+:term:`hashable`) this is often faster::
mylist = list(set(mylist))
@@ -1254,7 +1257,7 @@ difference is that a Python list can contain objects of many different types.
The ``array`` module also provides methods for creating arrays of fixed types
with compact representations, but they are slower to index than lists. Also
note that `NumPy `_
-and other third party packages define array-like structures with
+and other third-party packages define array-like structures with
various characteristics as well.
To get Lisp-style linked lists, you can emulate *cons cells* using tuples::
@@ -1324,7 +1327,7 @@ Or, you can use an extension that provides a matrix datatype; `NumPy
How do I apply a method or function to a sequence of objects?
-------------------------------------------------------------
-To call a method or function and accumulate the return values is a list,
+To call a method or function and accumulate the return values in a list,
a :term:`list comprehension` is an elegant solution::
result = [obj.method() for obj in mylist]
@@ -1340,6 +1343,7 @@ a plain :keyword:`for` loop will suffice::
for obj in mylist:
function(obj)
+
.. _faq-augmented-assignment-tuple-error:
Why does a_tuple[i] += ['item'] raise an exception when the addition works?
@@ -1444,7 +1448,7 @@ How can I sort one list by values from another list?
----------------------------------------------------
Merge them into an iterator of tuples, sort the resulting list, and then pick
-out the element you want. ::
+out the element you want.
>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
@@ -1504,14 +1508,15 @@ How do I check if an object is an instance of a given class or of a subclass of
Use the built-in function :func:`isinstance(obj, cls) `. You can
check if an object
is an instance of any of a number of classes by providing a tuple instead of a
-single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
-check whether an object is one of Python's built-in types, e.g.
+single class, for example, ``isinstance(obj, (class1, class2, ...))``, and can also
+check whether an object is one of Python's built-in types, for example,
``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
Note that :func:`isinstance` also checks for virtual inheritance from an
:term:`abstract base class`. So, the test will return ``True`` for a
registered class even if hasn't directly or indirectly inherited from it. To
-test for "true inheritance", scan the :term:`MRO` of the class:
+test for "true inheritance", scan the :term:`method resolution order` (MRO) of
+the class:
.. testcode::
@@ -1574,7 +1579,7 @@ call it::
What is delegation?
-------------------
-Delegation is an object oriented technique (also called a design pattern).
+Delegation is an object-oriented technique (also called a design pattern).
Let's say you have an object ``x`` and want to change the behaviour of just one
of its methods. You can create a new class that provides a new implementation
of the method you're interested in changing and delegates all other methods to
@@ -1645,7 +1650,7 @@ How can I organize my code to make it easier to change the base class?
You could assign the base class to an alias and derive from the alias. Then all
you have to change is the value assigned to the alias. Incidentally, this trick
-is also handy if you want to decide dynamically (e.g. depending on availability
+is also handy if you want to decide dynamically (such as depending on availability
of resources) which base class to use. Example::
class Base:
@@ -1710,9 +1715,9 @@ How can I overload constructors (or methods) in Python?
This answer actually applies to all methods, but the question usually comes up
first in the context of constructors.
-In C++ you'd write
+In C++ you'd write:
-.. code-block:: c
+.. code-block:: c++
class C {
C() { cout << "No arguments\n"; }
@@ -1731,7 +1736,7 @@ default arguments. For example::
This is not entirely equivalent, but close enough in practice.
-You could also try a variable-length argument list, e.g. ::
+You could also try a variable-length argument list, for example::
def __init__(self, *args):
...
@@ -1774,6 +1779,7 @@ to use private variable names at all.
The :ref:`private name mangling specifications `
for details and special cases.
+
My class defines __del__ but it is not called when I delete the object.
-----------------------------------------------------------------------
@@ -1783,7 +1789,7 @@ The :keyword:`del` statement does not necessarily call :meth:`~object.__del__` -
decrements the object's reference count, and if this reaches zero
:meth:`!__del__` is called.
-If your data structures contain circular links (e.g. a tree where each child has
+If your data structures contain circular links (for example, a tree where each child has
a parent reference and each parent has a list of children) the reference counts
will never go back to zero. Once in a while Python runs an algorithm to detect
such cycles, but the garbage collector might run some time after the last
@@ -1852,6 +1858,8 @@ to the object:
13891296
+.. _faq-identity-with-is:
+
When can I rely on identity tests with the *is* operator?
---------------------------------------------------------
@@ -1883,9 +1891,9 @@ are preferred. In particular, identity tests should not be used to check
constants such as :class:`int` and :class:`str` which aren't guaranteed to be
singletons::
- >>> a = 1000
- >>> b = 500
- >>> c = b + 500
+ >>> a = 10_000_000
+ >>> b = 5_000_000
+ >>> c = b + 5_000_000
>>> a is c
False
@@ -1954,9 +1962,9 @@ parent class:
.. testcode::
- from datetime import date
+ import datetime as dt
- class FirstOfMonthDate(date):
+ class FirstOfMonthDate(dt.date):
"Always choose the first day of the month"
def __new__(cls, year, month, day):
return super().__new__(cls, year, month, 1)
@@ -1999,7 +2007,7 @@ The two principal tools for caching methods are
former stores results at the instance level and the latter at the class
level.
-The *cached_property* approach only works with methods that do not take
+The ``cached_property`` approach only works with methods that do not take
any arguments. It does not create a reference to the instance. The
cached method result will be kept only as long as the instance is alive.
@@ -2008,7 +2016,7 @@ method result will be released right away. The disadvantage is that if
instances accumulate, so too will the accumulated method results. They
can grow without bound.
-The *lru_cache* approach works with methods that have :term:`hashable`
+The ``lru_cache`` approach works with methods that have :term:`hashable`
arguments. It creates a reference to the instance unless special
efforts are made to pass in weak references.
@@ -2042,11 +2050,11 @@ This example shows the various techniques::
# Depends on the station_id, date, and units.
The above example assumes that the *station_id* never changes. If the
-relevant instance attributes are mutable, the *cached_property* approach
+relevant instance attributes are mutable, the ``cached_property`` approach
can't be made to work because it cannot detect changes to the
attributes.
-To make the *lru_cache* approach work when the *station_id* is mutable,
+To make the ``lru_cache`` approach work when the *station_id* is mutable,
the class needs to define the :meth:`~object.__eq__` and :meth:`~object.__hash__`
methods so that the cache can detect relevant attribute updates::
@@ -2092,10 +2100,10 @@ one user but run as another, such as if you are testing with a web server.
Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set,
creation of a .pyc file is automatic if you're importing a module and Python
-has the ability (permissions, free space, etc...) to create a ``__pycache__``
+has the ability (permissions, free space, and so on) to create a ``__pycache__``
subdirectory and write the compiled module to that subdirectory.
-Running Python on a top level script is not considered an import and no
+Running Python on a top-level script is not considered an import and no
``.pyc`` will be created. For example, if you have a top-level module
``foo.py`` that imports another module ``xyz.py``, when you run ``foo`` (by
typing ``python foo.py`` as a shell command), a ``.pyc`` will be created for
@@ -2114,7 +2122,7 @@ the ``compile()`` function in that module interactively::
This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same
location as ``foo.py`` (or you can override that with the optional parameter
-``cfile``).
+*cfile*).
You can also automatically compile all files in a directory or directories using
the :mod:`compileall` module. You can do it from the shell prompt by running
@@ -2219,7 +2227,7 @@ changed module, do this::
importlib.reload(modname)
Warning: this technique is not 100% fool-proof. In particular, modules
-containing statements like ::
+containing statements like::
from modname import some_objects
diff --git a/Doc/glossary.rst b/Doc/glossary.rst
index 24b95b88dfb651..6151143a97b420 100644
--- a/Doc/glossary.rst
+++ b/Doc/glossary.rst
@@ -951,6 +951,16 @@ Glossary
to locks exist such as queues, producer/consumer patterns, and
thread-local state. See also :term:`deadlock`, and :term:`reentrant`.
+ lock-free
+ An operation that does not acquire any :term:`lock` and uses atomic CPU
+ instructions to ensure correctness. Lock-free operations can execute
+ concurrently without blocking each other and cannot be blocked by
+ operations that hold locks. In :term:`free-threaded `
+ Python, built-in types like :class:`dict` and :class:`list` provide
+ lock-free read operations, which means other threads may observe
+ intermediate states during multi-step modifications even when those
+ modifications hold the :term:`per-object lock`.
+
loader
An object that loads a module.
It must define the :meth:`!exec_module` and :meth:`!create_module` methods
@@ -1217,6 +1227,16 @@ Glossary
`, the :class:`inspect.Parameter` class, the
:ref:`function` section, and :pep:`362`.
+ per-object lock
+ A :term:`lock` associated with an individual object instance rather than
+ a global lock shared across all objects. In :term:`free-threaded
+ ` Python, built-in types like :class:`dict` and
+ :class:`list` use per-object locks to allow concurrent operations on
+ different objects while serializing operations on the same object.
+ Operations that hold the per-object lock prevent other locking operations
+ on the same object from proceeding, but do not block :term:`lock-free`
+ operations.
+
path entry
A single location on the :term:`import path` which the :term:`path
based finder` consults to find modules for importing.
@@ -1339,7 +1359,7 @@ Glossary
'email.mime.text'
race condition
- A condition of a program where the its behavior
+ A condition of a program where the behavior
depends on the relative timing or ordering of events, particularly in
multi-threaded programs. Race conditions can lead to
:term:`non-deterministic` behavior and bugs that are difficult to
diff --git a/Doc/howto/enum.rst b/Doc/howto/enum.rst
index 7713aede6d564a..93850b57af2c65 100644
--- a/Doc/howto/enum.rst
+++ b/Doc/howto/enum.rst
@@ -965,75 +965,16 @@ want one of them to be the value::
Finer Points
-^^^^^^^^^^^^
-
-Supported ``__dunder__`` names
-""""""""""""""""""""""""""""""
-
-:attr:`~enum.EnumType.__members__` is a read-only ordered mapping of ``member_name``:``member``
-items. It is only available on the class.
-
-:meth:`~object.__new__`, if specified, must create and return the enum members; it is
-also a very good idea to set the member's :attr:`~Enum._value_` appropriately. Once
-all the members are created it is no longer used.
-
-
-Supported ``_sunder_`` names
-""""""""""""""""""""""""""""
+------------
-- :attr:`~Enum._name_` -- name of the member
-- :attr:`~Enum._value_` -- value of the member; can be set in ``__new__``
-- :meth:`~Enum._missing_` -- a lookup function used when a value is not found;
- may be overridden
-- :attr:`~Enum._ignore_` -- a list of names, either as a :class:`list` or a
- :class:`str`, that will not be transformed into members, and will be removed
- from the final class
-- :meth:`~Enum._generate_next_value_` -- used to get an appropriate value for
- an enum member; may be overridden
-- :meth:`~Enum._add_alias_` -- adds a new name as an alias to an existing
- member.
-- :meth:`~Enum._add_value_alias_` -- adds a new value as an alias to an
- existing member. See `MultiValueEnum`_ for an example.
+Supported ``__dunder__`` and ``_sunder_`` names
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- .. note::
-
- For standard :class:`Enum` classes the next value chosen is the highest
- value seen incremented by one.
-
- For :class:`Flag` classes the next value chosen will be the next highest
- power-of-two.
-
- .. versionchanged:: 3.13
- Prior versions would use the last seen value instead of the highest value.
-
-.. versionadded:: 3.6 ``_missing_``, ``_order_``, ``_generate_next_value_``
-.. versionadded:: 3.7 ``_ignore_``
-.. versionadded:: 3.13 ``_add_alias_``, ``_add_value_alias_``
-
-To help keep Python 2 / Python 3 code in sync an :attr:`~Enum._order_` attribute can
-be provided. It will be checked against the actual order of the enumeration
-and raise an error if the two do not match::
-
- >>> class Color(Enum):
- ... _order_ = 'RED GREEN BLUE'
- ... RED = 1
- ... BLUE = 3
- ... GREEN = 2
- ...
- Traceback (most recent call last):
- ...
- TypeError: member order does not match _order_:
- ['RED', 'BLUE', 'GREEN']
- ['RED', 'GREEN', 'BLUE']
-
-.. note::
-
- In Python 2 code the :attr:`~Enum._order_` attribute is necessary as definition
- order is lost before it can be recorded.
+The supported ``__dunder__`` and ``_sunder_`` names can be found in the :ref:`Enum API documentation `.
_Private__names
-"""""""""""""""
+^^^^^^^^^^^^^^^
:ref:`Private names ` are not converted to enum members,
but remain normal attributes.
@@ -1042,7 +983,7 @@ but remain normal attributes.
``Enum`` member type
-""""""""""""""""""""
+^^^^^^^^^^^^^^^^^^^^
Enum members are instances of their enum class, and are normally accessed as
``EnumClass.member``. In certain situations, such as writing custom enum
@@ -1055,7 +996,7 @@ recommended.
Creating members that are mixed with other data types
-"""""""""""""""""""""""""""""""""""""""""""""""""""""
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When subclassing other data types, such as :class:`int` or :class:`str`, with
an :class:`Enum`, all values after the ``=`` are passed to that data type's
@@ -1069,7 +1010,7 @@ constructor. For example::
Boolean value of ``Enum`` classes and members
-"""""""""""""""""""""""""""""""""""""""""""""
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Enum classes that are mixed with non-:class:`Enum` types (such as
:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
@@ -1084,7 +1025,7 @@ Plain :class:`Enum` classes always evaluate as :data:`True`.
``Enum`` classes with methods
-"""""""""""""""""""""""""""""
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you give your enum subclass extra methods, like the `Planet`_
class below, those methods will show up in a :func:`dir` of the member,
@@ -1097,7 +1038,7 @@ but not of the class::
Combining members of ``Flag``
-"""""""""""""""""""""""""""""
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Iterating over a combination of :class:`Flag` members will only return the members that
are comprised of a single bit::
@@ -1117,7 +1058,7 @@ are comprised of a single bit::
``Flag`` and ``IntFlag`` minutia
-""""""""""""""""""""""""""""""""
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Using the following snippet for our examples::
@@ -1478,6 +1419,7 @@ alias::
behaviors as well as disallowing aliases. If the only desired change is
disallowing aliases, the :func:`unique` decorator can be used instead.
+.. _multi-value-enum:
MultiValueEnum
^^^^^^^^^^^^^^^^^
diff --git a/Doc/howto/free-threading-extensions.rst b/Doc/howto/free-threading-extensions.rst
index 83eba8cfea3969..2f089a3d89680a 100644
--- a/Doc/howto/free-threading-extensions.rst
+++ b/Doc/howto/free-threading-extensions.rst
@@ -384,6 +384,30 @@ Important Considerations
internal extension state, standard mutexes or other synchronization
primitives might be more appropriate.
+.. _per-object-locks:
+
+Per-Object Locks (``ob_mutex``)
+...............................
+
+In the free-threaded build, each Python object contains a :c:member:`~PyObject.ob_mutex`
+field of type :c:type:`PyMutex`. This mutex is **reserved for use by the
+critical section API** (:c:macro:`Py_BEGIN_CRITICAL_SECTION` /
+:c:macro:`Py_END_CRITICAL_SECTION`).
+
+.. warning::
+
+ Do **not** lock ``ob_mutex`` directly with ``PyMutex_Lock(&obj->ob_mutex)``.
+ Mixing direct ``PyMutex_Lock`` calls with the critical section API on the
+ same mutex can cause deadlocks.
+
+Even if your own code never uses critical sections on a particular object type,
+**CPython internals may use the critical section API on any Python object**.
+
+If your extension type needs its own lock, add a separate :c:type:`PyMutex`
+field (or another synchronization primitive) to your object struct.
+:c:type:`PyMutex` is very lightweight, so there is negligible cost to having
+an additional one.
+
Building Extensions for the Free-Threaded Build
===============================================
diff --git a/Doc/howto/instrumentation.rst b/Doc/howto/instrumentation.rst
index b3db1189e5dcbc..06c1ae40da5e67 100644
--- a/Doc/howto/instrumentation.rst
+++ b/Doc/howto/instrumentation.rst
@@ -341,6 +341,84 @@ Available static markers
.. versionadded:: 3.8
+C Entry Points
+^^^^^^^^^^^^^^
+
+To simplify triggering of DTrace markers, Python's C API comes with a number
+of helper functions that mirror each static marker. On builds of Python without
+DTrace enabled, these do nothing.
+
+In general, it is not necessary to call these yourself, as Python will do
+it for you.
+
+.. list-table::
+ :widths: 50 25 25
+ :header-rows: 1
+
+ * * C API Function
+ * Static Marker
+ * Notes
+ * * .. c:function:: void PyDTrace_LINE(const char *arg0, const char *arg1, int arg2)
+ * :c:func:`!line`
+ *
+ * * .. c:function:: void PyDTrace_FUNCTION_ENTRY(const char *arg0, const char *arg1, int arg2)
+ * :c:func:`!function__entry`
+ *
+ * * .. c:function:: void PyDTrace_FUNCTION_RETURN(const char *arg0, const char *arg1, int arg2)
+ * :c:func:`!function__return`
+ *
+ * * .. c:function:: void PyDTrace_GC_START(int arg0)
+ * :c:func:`!gc__start`
+ *
+ * * .. c:function:: void PyDTrace_GC_DONE(Py_ssize_t arg0)
+ * :c:func:`!gc__done`
+ *
+ * * .. c:function:: void PyDTrace_INSTANCE_NEW_START(int arg0)
+ * :c:func:`!instance__new__start`
+ * Not used by Python
+ * * .. c:function:: void PyDTrace_INSTANCE_NEW_DONE(int arg0)
+ * :c:func:`!instance__new__done`
+ * Not used by Python
+ * * .. c:function:: void PyDTrace_INSTANCE_DELETE_START(int arg0)
+ * :c:func:`!instance__delete__start`
+ * Not used by Python
+ * * .. c:function:: void PyDTrace_INSTANCE_DELETE_DONE(int arg0)
+ * :c:func:`!instance__delete__done`
+ * Not used by Python
+ * * .. c:function:: void PyDTrace_IMPORT_FIND_LOAD_START(const char *arg0)
+ * :c:func:`!import__find__load__start`
+ *
+ * * .. c:function:: void PyDTrace_IMPORT_FIND_LOAD_DONE(const char *arg0, int arg1)
+ * :c:func:`!import__find__load__done`
+ *
+ * * .. c:function:: void PyDTrace_AUDIT(const char *arg0, void *arg1)
+ * :c:func:`!audit`
+ *
+
+
+C Probing Checks
+^^^^^^^^^^^^^^^^
+
+.. c:function:: int PyDTrace_LINE_ENABLED(void)
+.. c:function:: int PyDTrace_FUNCTION_ENTRY_ENABLED(void)
+.. c:function:: int PyDTrace_FUNCTION_RETURN_ENABLED(void)
+.. c:function:: int PyDTrace_GC_START_ENABLED(void)
+.. c:function:: int PyDTrace_GC_DONE_ENABLED(void)
+.. c:function:: int PyDTrace_INSTANCE_NEW_START_ENABLED(void)
+.. c:function:: int PyDTrace_INSTANCE_NEW_DONE_ENABLED(void)
+.. c:function:: int PyDTrace_INSTANCE_DELETE_START_ENABLED(void)
+.. c:function:: int PyDTrace_INSTANCE_DELETE_DONE_ENABLED(void)
+.. c:function:: int PyDTrace_IMPORT_FIND_LOAD_START_ENABLED(void)
+.. c:function:: int PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED(void)
+.. c:function:: int PyDTrace_AUDIT_ENABLED(void)
+
+ All calls to ``PyDTrace`` functions must be guarded by a call to one
+ of these functions. This allows Python to minimize performance impact
+ when probing is disabled.
+
+ On builds without DTrace enabled, these functions do nothing and return
+ ``0``.
+
SystemTap Tapsets
-----------------
diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst
index 9633bc75f2c914..b87ac93296b915 100644
--- a/Doc/howto/logging-cookbook.rst
+++ b/Doc/howto/logging-cookbook.rst
@@ -1564,9 +1564,6 @@ process. This can be set up using a process management tool such as Supervisor -
Using file rotation
-------------------
-.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
-.. (see )
-
Sometimes you want to let a log file grow to a certain size, then open a new
file and log to that. You may want to keep a certain number of these files, and
when that many files have been created, rotate the files so that the number of
diff --git a/Doc/howto/logging.rst b/Doc/howto/logging.rst
index b7225ff1c2cbfc..454e2f4930e724 100644
--- a/Doc/howto/logging.rst
+++ b/Doc/howto/logging.rst
@@ -28,7 +28,7 @@ When to use logging
^^^^^^^^^^^^^^^^^^^
You can access logging functionality by creating a logger via ``logger =
-getLogger(__name__)``, and then calling the logger's :meth:`~Logger.debug`,
+logging.getLogger(__name__)``, and then calling the logger's :meth:`~Logger.debug`,
:meth:`~Logger.info`, :meth:`~Logger.warning`, :meth:`~Logger.error` and
:meth:`~Logger.critical` methods. To determine when to use logging, and to see
which logger methods to use when, see the table below. It states, for each of a
diff --git a/Doc/improve-page-nojs.rst b/Doc/improve-page-nojs.rst
new file mode 100644
index 00000000000000..91b3a88b95d38b
--- /dev/null
+++ b/Doc/improve-page-nojs.rst
@@ -0,0 +1,29 @@
+:orphan:
+
+****************************
+Improve a documentation page
+****************************
+
+.. This is the no-javascript version of this page. The one most people
+ will see (with JavaScript enabled) is improve-page.rst. If you edit
+ this page, please also edit that one, and vice versa.
+
+.. only:: html and not epub
+
+We are always interested to hear ideas about improvements to the documentation.
+
+.. only:: translation
+
+ If the bug or suggested improvement concerns the translation of this
+ documentation, open an issue or edit the page in
+ `translation's repository `_ instead.
+
+You have a few ways to ask questions or suggest changes:
+
+- You can start a discussion about the page on the Python discussion forum.
+ This link will start a topic in the Documentation category:
+ `New Documentation topic `_.
+
+- You can open an issue on the Python GitHub issue tracker. This link will
+ create a new issue with the "docs" label:
+ `New docs issue `_.
diff --git a/Doc/improve-page.rst b/Doc/improve-page.rst
new file mode 100644
index 00000000000000..dc89fcb22fbb59
--- /dev/null
+++ b/Doc/improve-page.rst
@@ -0,0 +1,65 @@
+:orphan:
+
+****************************
+Improve a documentation page
+****************************
+
+.. This is the JavaScript-enabled version of this page. Another version
+ (for those with JavaScript disabled) is improve-page-nojs.rst. If you
+ edit this page, please also edit that one, and vice versa.
+
+.. only:: html and not epub
+
+ .. raw:: html
+
+
+
+We are always interested to hear ideas about improvements to the documentation.
+
+You were reading "PAGETITLE" at ``_. The source for that page is on
+`GitHub `_.
+
+.. only:: translation
+
+ If the bug or suggested improvement concerns the translation of this
+ documentation, open an issue or edit the page in
+ `translation's repository `_ instead.
+
+You have a few ways to ask questions or suggest changes:
+
+- You can start a discussion about the page on the Python discussion forum.
+ This link will start a pre-populated topic:
+ `Question about page "PAGETITLE" `_.
+
+- You can open an issue on the Python GitHub issue tracker. This link will
+ create a new pre-populated issue:
+ `Docs: problem with page "PAGETITLE" `_.
+
+- You can `edit the page on GitHub `_
+ to open a pull request and begin the contribution process.
diff --git a/Doc/includes/tzinfo_examples.py b/Doc/includes/tzinfo_examples.py
index 1fa6e615e46a76..762b1b62fc871d 100644
--- a/Doc/includes/tzinfo_examples.py
+++ b/Doc/includes/tzinfo_examples.py
@@ -1,68 +1,70 @@
-from datetime import tzinfo, timedelta, datetime
-
-ZERO = timedelta(0)
-HOUR = timedelta(hours=1)
-SECOND = timedelta(seconds=1)
+import datetime as dt
# A class capturing the platform's idea of local time.
# (May result in wrong values on historical times in
# timezones where UTC offset and/or the DST rules had
# changed in the past.)
-import time as _time
+import time
+
+ZERO = dt.timedelta(0)
+HOUR = dt.timedelta(hours=1)
+SECOND = dt.timedelta(seconds=1)
-STDOFFSET = timedelta(seconds = -_time.timezone)
-if _time.daylight:
- DSTOFFSET = timedelta(seconds = -_time.altzone)
+STDOFFSET = dt.timedelta(seconds=-time.timezone)
+if time.daylight:
+ DSTOFFSET = dt.timedelta(seconds=-time.altzone)
else:
DSTOFFSET = STDOFFSET
DSTDIFF = DSTOFFSET - STDOFFSET
-class LocalTimezone(tzinfo):
- def fromutc(self, dt):
- assert dt.tzinfo is self
- stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
- args = _time.localtime(stamp)[:6]
+class LocalTimezone(dt.tzinfo):
+
+ def fromutc(self, when):
+ assert when.tzinfo is self
+ stamp = (when - dt.datetime(1970, 1, 1, tzinfo=self)) // SECOND
+ args = time.localtime(stamp)[:6]
dst_diff = DSTDIFF // SECOND
# Detect fold
- fold = (args == _time.localtime(stamp - dst_diff))
- return datetime(*args, microsecond=dt.microsecond,
- tzinfo=self, fold=fold)
+ fold = (args == time.localtime(stamp - dst_diff))
+ return dt.datetime(*args, microsecond=when.microsecond,
+ tzinfo=self, fold=fold)
- def utcoffset(self, dt):
- if self._isdst(dt):
+ def utcoffset(self, when):
+ if self._isdst(when):
return DSTOFFSET
else:
return STDOFFSET
- def dst(self, dt):
- if self._isdst(dt):
+ def dst(self, when):
+ if self._isdst(when):
return DSTDIFF
else:
return ZERO
- def tzname(self, dt):
- return _time.tzname[self._isdst(dt)]
+ def tzname(self, when):
+ return time.tzname[self._isdst(when)]
- def _isdst(self, dt):
- tt = (dt.year, dt.month, dt.day,
- dt.hour, dt.minute, dt.second,
- dt.weekday(), 0, 0)
- stamp = _time.mktime(tt)
- tt = _time.localtime(stamp)
+ def _isdst(self, when):
+ tt = (when.year, when.month, when.day,
+ when.hour, when.minute, when.second,
+ when.weekday(), 0, 0)
+ stamp = time.mktime(tt)
+ tt = time.localtime(stamp)
return tt.tm_isdst > 0
+
Local = LocalTimezone()
# A complete implementation of current DST rules for major US time zones.
-def first_sunday_on_or_after(dt):
- days_to_go = 6 - dt.weekday()
+def first_sunday_on_or_after(when):
+ days_to_go = 6 - when.weekday()
if days_to_go:
- dt += timedelta(days_to_go)
- return dt
+ when += dt.timedelta(days_to_go)
+ return when
# US DST Rules
@@ -75,21 +77,22 @@ def first_sunday_on_or_after(dt):
#
# In the US, since 2007, DST starts at 2am (standard time) on the second
# Sunday in March, which is the first Sunday on or after Mar 8.
-DSTSTART_2007 = datetime(1, 3, 8, 2)
+DSTSTART_2007 = dt.datetime(1, 3, 8, 2)
# and ends at 2am (DST time) on the first Sunday of Nov.
-DSTEND_2007 = datetime(1, 11, 1, 2)
+DSTEND_2007 = dt.datetime(1, 11, 1, 2)
# From 1987 to 2006, DST used to start at 2am (standard time) on the first
# Sunday in April and to end at 2am (DST time) on the last
# Sunday of October, which is the first Sunday on or after Oct 25.
-DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
-DSTEND_1987_2006 = datetime(1, 10, 25, 2)
+DSTSTART_1987_2006 = dt.datetime(1, 4, 1, 2)
+DSTEND_1987_2006 = dt.datetime(1, 10, 25, 2)
# From 1967 to 1986, DST used to start at 2am (standard time) on the last
# Sunday in April (the one on or after April 24) and to end at 2am (DST time)
# on the last Sunday of October, which is the first Sunday
# on or after Oct 25.
-DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
+DSTSTART_1967_1986 = dt.datetime(1, 4, 24, 2)
DSTEND_1967_1986 = DSTEND_1987_2006
+
def us_dst_range(year):
# Find start and end times for US DST. For years before 1967, return
# start = end for no DST.
@@ -100,17 +103,17 @@ def us_dst_range(year):
elif 1966 < year < 1987:
dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
else:
- return (datetime(year, 1, 1), ) * 2
+ return (dt.datetime(year, 1, 1), ) * 2
start = first_sunday_on_or_after(dststart.replace(year=year))
end = first_sunday_on_or_after(dstend.replace(year=year))
return start, end
-class USTimeZone(tzinfo):
+class USTimeZone(dt.tzinfo):
def __init__(self, hours, reprname, stdname, dstname):
- self.stdoffset = timedelta(hours=hours)
+ self.stdoffset = dt.timedelta(hours=hours)
self.reprname = reprname
self.stdname = stdname
self.dstname = dstname
@@ -118,45 +121,45 @@ def __init__(self, hours, reprname, stdname, dstname):
def __repr__(self):
return self.reprname
- def tzname(self, dt):
- if self.dst(dt):
+ def tzname(self, when):
+ if self.dst(when):
return self.dstname
else:
return self.stdname
- def utcoffset(self, dt):
- return self.stdoffset + self.dst(dt)
+ def utcoffset(self, when):
+ return self.stdoffset + self.dst(when)
- def dst(self, dt):
- if dt is None or dt.tzinfo is None:
+ def dst(self, when):
+ if when is None or when.tzinfo is None:
# An exception may be sensible here, in one or both cases.
# It depends on how you want to treat them. The default
# fromutc() implementation (called by the default astimezone()
- # implementation) passes a datetime with dt.tzinfo is self.
+ # implementation) passes a datetime with when.tzinfo is self.
return ZERO
- assert dt.tzinfo is self
- start, end = us_dst_range(dt.year)
+ assert when.tzinfo is self
+ start, end = us_dst_range(when.year)
# Can't compare naive to aware objects, so strip the timezone from
- # dt first.
- dt = dt.replace(tzinfo=None)
- if start + HOUR <= dt < end - HOUR:
+ # when first.
+ when = when.replace(tzinfo=None)
+ if start + HOUR <= when < end - HOUR:
# DST is in effect.
return HOUR
- if end - HOUR <= dt < end:
- # Fold (an ambiguous hour): use dt.fold to disambiguate.
- return ZERO if dt.fold else HOUR
- if start <= dt < start + HOUR:
+ if end - HOUR <= when < end:
+ # Fold (an ambiguous hour): use when.fold to disambiguate.
+ return ZERO if when.fold else HOUR
+ if start <= when < start + HOUR:
# Gap (a non-existent hour): reverse the fold rule.
- return HOUR if dt.fold else ZERO
+ return HOUR if when.fold else ZERO
# DST is off.
return ZERO
- def fromutc(self, dt):
- assert dt.tzinfo is self
- start, end = us_dst_range(dt.year)
+ def fromutc(self, when):
+ assert when.tzinfo is self
+ start, end = us_dst_range(when.year)
start = start.replace(tzinfo=self)
end = end.replace(tzinfo=self)
- std_time = dt + self.stdoffset
+ std_time = when + self.stdoffset
dst_time = std_time + HOUR
if end <= dst_time < end + HOUR:
# Repeated hour
diff --git a/Doc/installing/index.rst b/Doc/installing/index.rst
index 3a485a43a5a751..412005f3ec82f4 100644
--- a/Doc/installing/index.rst
+++ b/Doc/installing/index.rst
@@ -6,8 +6,6 @@
Installing Python Modules
*************************
-:Email: distutils-sig@python.org
-
As a popular open source development project, Python has an active
supporting community of contributors and users that also make their software
available for other Python developers to use under open source license terms.
diff --git a/Doc/library/__future__.rst b/Doc/library/__future__.rst
index 5d916b30112d3c..749e4543c5b823 100644
--- a/Doc/library/__future__.rst
+++ b/Doc/library/__future__.rst
@@ -15,7 +15,7 @@ before the release in which the feature becomes standard.
While these future statements are given additional special meaning by the
Python compiler, they are still executed like any other import statement and
-the :mod:`__future__` exists and is handled by the import system the same way
+the :mod:`!__future__` exists and is handled by the import system the same way
any other Python module would be. This design serves three purposes:
* To avoid confusing existing tools that analyze import statements and expect to
@@ -23,17 +23,17 @@ any other Python module would be. This design serves three purposes:
* To document when incompatible changes were introduced, and when they will be
--- or were --- made mandatory. This is a form of executable documentation, and
- can be inspected programmatically via importing :mod:`__future__` and examining
+ can be inspected programmatically via importing :mod:`!__future__` and examining
its contents.
* To ensure that :ref:`future statements ` run under releases prior to
- Python 2.1 at least yield runtime exceptions (the import of :mod:`__future__`
+ Python 2.1 at least yield runtime exceptions (the import of :mod:`!__future__`
will fail, because there was no module of that name prior to 2.1).
Module Contents
---------------
-No feature description will ever be deleted from :mod:`__future__`. Since its
+No feature description will ever be deleted from :mod:`!__future__`. Since its
introduction in Python 2.1 the following features have found their way into the
language using this mechanism:
diff --git a/Doc/library/abc.rst b/Doc/library/abc.rst
index 49e541a9d9b1cb..8112cfee7d204d 100644
--- a/Doc/library/abc.rst
+++ b/Doc/library/abc.rst
@@ -4,10 +4,6 @@
.. module:: abc
:synopsis: Abstract base classes according to :pep:`3119`.
-.. moduleauthor:: Guido van Rossum
-.. sectionauthor:: Georg Brandl
-.. much of the content adapted from docstrings
-
**Source code:** :source:`Lib/abc.py`
--------------
diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst
index f4109fe0e5f2bf..5a463ee9821d61 100644
--- a/Doc/library/argparse.rst
+++ b/Doc/library/argparse.rst
@@ -4,16 +4,13 @@
.. module:: argparse
:synopsis: Command-line option and argument parsing library.
-.. moduleauthor:: Steven Bethard
-.. sectionauthor:: Steven Bethard
-
.. versionadded:: 3.2
**Source code:** :source:`Lib/argparse.py`
.. note::
- While :mod:`argparse` is the default recommended standard library module
+ While :mod:`!argparse` is the default recommended standard library module
for implementing basic command line applications, authors with more
exacting requirements for exactly how their command line applications
behave may find it doesn't provide the necessary level of control.
@@ -605,18 +602,13 @@ choices (if specified) or subparser names, along with a "maybe you meant"
suggestion if a close match is found. Note that this only applies for arguments
when the choices specified are strings::
- >>> parser = argparse.ArgumentParser(description='Process some integers.',
- suggest_on_error=True)
- >>> parser.add_argument('--action', choices=['sum', 'max'])
- >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
- ... help='an integer for the accumulator')
- >>> parser.parse_args(['--action', 'sumn', 1, 2, 3])
- tester.py: error: argument --action: invalid choice: 'sumn', maybe you meant 'sum'? (choose from 'sum', 'max')
-
-You can disable suggestions by setting ``suggest_on_error`` to ``False``::
+ >>> parser = argparse.ArgumentParser(suggest_on_error=True)
+ >>> parser.add_argument('--action', choices=['debug', 'dryrun'])
+ >>> parser.parse_args(['--action', 'debugg'])
+ usage: tester.py [-h] [--action {debug,dryrun}]
+ tester.py: error: argument --action: invalid choice: 'debugg', maybe you meant 'debug'? (choose from debug, dryrun)
- >>> parser = argparse.ArgumentParser(description='Process some integers.',
- suggest_on_error=False)
+You can disable suggestions by setting ``suggest_on_error`` to ``False``.
.. versionadded:: 3.14
.. versionchanged:: 3.15
@@ -706,6 +698,8 @@ The add_argument() method
* deprecated_ - Whether or not use of the argument is deprecated.
+ The method returns an :class:`Action` object representing the argument.
+
The following sections describe how each of these are used.
@@ -747,9 +741,9 @@ By default, :mod:`!argparse` automatically handles the internal naming and
display names of arguments, simplifying the process without requiring
additional configuration.
As such, you do not need to specify the dest_ and metavar_ parameters.
-The dest_ parameter defaults to the argument name with underscores ``_``
-replacing hyphens ``-`` . The metavar_ parameter defaults to the
-upper-cased name. For example::
+For optional arguments, the dest_ parameter defaults to the argument name, with
+underscores ``_`` replacing hyphens ``-``. The metavar_ parameter defaults to
+the upper-cased name. For example::
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo-bar')
@@ -1771,7 +1765,7 @@ Subcommands
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)
- Note that the object returned by :meth:`parse_args` will only contain
+ Note that the object returned by :meth:`~ArgumentParser.parse_args` will only contain
attributes for the main parser and the subparser that was selected by the
command line (and not any other subparsers). So in the example above, when
the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
@@ -1814,7 +1808,7 @@ Subcommands
-h, --help show this help message and exit
--baz {X,Y,Z} baz help
- The :meth:`add_subparsers` method also supports ``title`` and ``description``
+ The :meth:`~ArgumentParser.add_subparsers` method also supports ``title`` and ``description``
keyword arguments. When either is present, the subparser's commands will
appear in their own group in the help output. For example::
@@ -1835,34 +1829,8 @@ Subcommands
{foo,bar} additional help
- Furthermore, :meth:`~_SubParsersAction.add_parser` supports an additional
- *aliases* argument,
- which allows multiple strings to refer to the same subparser. This example,
- like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
-
- >>> parser = argparse.ArgumentParser()
- >>> subparsers = parser.add_subparsers()
- >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
- >>> checkout.add_argument('foo')
- >>> parser.parse_args(['co', 'bar'])
- Namespace(foo='bar')
-
- :meth:`~_SubParsersAction.add_parser` supports also an additional
- *deprecated* argument, which allows to deprecate the subparser.
-
- >>> import argparse
- >>> parser = argparse.ArgumentParser(prog='chicken.py')
- >>> subparsers = parser.add_subparsers()
- >>> run = subparsers.add_parser('run')
- >>> fly = subparsers.add_parser('fly', deprecated=True)
- >>> parser.parse_args(['fly']) # doctest: +SKIP
- chicken.py: warning: command 'fly' is deprecated
- Namespace()
-
- .. versionadded:: 3.13
-
One particularly effective way of handling subcommands is to combine the use
- of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
+ of the :meth:`~ArgumentParser.add_subparsers` method with calls to :meth:`~ArgumentParser.set_defaults` so
that each subparser knows which Python function it should execute. For
example::
@@ -1898,12 +1866,12 @@ Subcommands
>>> args.func(args)
((XYZYX))
- This way, you can let :meth:`parse_args` do the job of calling the
+ This way, you can let :meth:`~ArgumentParser.parse_args` do the job of calling the
appropriate function after argument parsing is complete. Associating
functions with actions like this is typically the easiest way to handle the
different actions for each of your subparsers. However, if it is necessary
to check the name of the subparser that was invoked, the ``dest`` keyword
- argument to the :meth:`add_subparsers` call will work::
+ argument to the :meth:`~ArgumentParser.add_subparsers` call will work::
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(dest='subparser_name')
@@ -1922,6 +1890,43 @@ Subcommands
the main parser.
+.. method:: _SubParsersAction.add_parser(name, *, help=None, aliases=None, \
+ deprecated=False, **kwargs)
+
+ Create and return a new :class:`ArgumentParser` object for the
+ subcommand *name*.
+
+ The *name* argument is the name of the sub-command.
+
+ The *help* argument provides a short description for this sub-command.
+
+ The *aliases* argument allows providing alternative names for this
+ sub-command. For example::
+
+ >>> parser = argparse.ArgumentParser()
+ >>> subparsers = parser.add_subparsers()
+ >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
+ >>> checkout.add_argument('foo')
+ >>> parser.parse_args(['co', 'bar'])
+ Namespace(foo='bar')
+
+ The *deprecated* argument, if ``True``, marks the sub-command as
+ deprecated and will issue a warning when used. For example::
+
+ >>> parser = argparse.ArgumentParser(prog='chicken.py')
+ >>> subparsers = parser.add_subparsers()
+ >>> fly = subparsers.add_parser('fly', deprecated=True)
+ >>> args = parser.parse_args(['fly'])
+ chicken.py: warning: command 'fly' is deprecated
+ Namespace()
+
+ All other keyword arguments are passed directly to the
+ :class:`!ArgumentParser` constructor.
+
+ .. versionadded:: 3.13
+ Added the *deprecated* parameter.
+
+
FileType objects
^^^^^^^^^^^^^^^^
diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst
index bf37540e5faf42..9660ad70932764 100644
--- a/Doc/library/ast.rst
+++ b/Doc/library/ast.rst
@@ -4,9 +4,6 @@
.. module:: ast
:synopsis: Abstract Syntax Tree classes and manipulation.
-.. sectionauthor:: Martin v. Lรถwis
-.. sectionauthor:: Georg Brandl
-
.. testsetup::
import ast
@@ -15,7 +12,7 @@
--------------
-The :mod:`ast` module helps Python applications to process trees of the Python
+The :mod:`!ast` module helps Python applications to process trees of the Python
abstract syntax grammar. The abstract syntax itself might change with each
Python release; this module helps to find out programmatically what the current
grammar looks like.
@@ -46,7 +43,7 @@ Node classes
This is the base of all AST node classes. The actual node classes are
derived from the :file:`Parser/Python.asdl` file, which is reproduced
:ref:`above `. They are defined in the :mod:`!_ast` C
- module and re-exported in :mod:`ast`.
+ module and re-exported in :mod:`!ast`.
There is one class defined for each left-hand side symbol in the abstract
grammar (for example, :class:`ast.stmt` or :class:`ast.expr`). In addition,
@@ -1114,7 +1111,8 @@ Imports
names=[
alias(name='x'),
alias(name='y'),
- alias(name='z')])])
+ alias(name='z')],
+ is_lazy=0)])
.. class:: ImportFrom(module, names, level)
@@ -1135,7 +1133,8 @@ Imports
alias(name='x'),
alias(name='y'),
alias(name='z')],
- level=0)])
+ level=0,
+ is_lazy=0)])
.. class:: alias(name, asname)
@@ -1153,7 +1152,8 @@ Imports
names=[
alias(name='a', asname='b'),
alias(name='c')],
- level=2)])
+ level=2,
+ is_lazy=0)])
Control flow
^^^^^^^^^^^^
@@ -2200,10 +2200,10 @@ Async and await
occurrences of the same value (for example, :class:`ast.Add`).
-:mod:`ast` helpers
-------------------
+:mod:`!ast` helpers
+-------------------
-Apart from the node classes, the :mod:`ast` module defines these utility functions
+Apart from the node classes, the :mod:`!ast` module defines these utility functions
and classes for traversing abstract syntax trees:
.. function:: parse(source, filename='', mode='exec', *, type_comments=False, feature_version=None, optimize=-1, module=None)
@@ -2576,7 +2576,7 @@ Command-line usage
.. versionadded:: 3.9
-The :mod:`ast` module can be executed as a script from the command line.
+The :mod:`!ast` module can be executed as a script from the command line.
It is as simple as:
.. code-block:: sh
diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst
index 72f484fd1cbe77..bdb24b3a58c267 100644
--- a/Doc/library/asyncio-eventloop.rst
+++ b/Doc/library/asyncio-eventloop.rst
@@ -297,8 +297,9 @@ clocks to track time.
are called is undefined.
The optional positional *args* will be passed to the callback when
- it is called. If you want the callback to be called with keyword
- arguments use :func:`functools.partial`.
+ it is called. Use :func:`functools.partial`
+ :ref:`to pass keyword arguments ` to
+ *callback*.
An optional keyword-only *context* argument allows specifying a
custom :class:`contextvars.Context` for the *callback* to run in.
@@ -1034,8 +1035,8 @@ Watching file descriptors
.. method:: loop.add_writer(fd, callback, *args)
Start monitoring the *fd* file descriptor for write availability and
- invoke *callback* with the specified arguments once *fd* is available for
- writing.
+ invoke *callback* with the specified arguments *args* once *fd* is
+ available for writing.
Any preexisting callback registered for *fd* is cancelled and replaced by
*callback*.
@@ -1308,7 +1309,8 @@ Unix signals
.. method:: loop.add_signal_handler(signum, callback, *args)
- Set *callback* as the handler for the *signum* signal.
+ Set *callback* as the handler for the *signum* signal,
+ passing *args* as positional arguments.
The callback will be invoked by *loop*, along with other queued callbacks
and runnable coroutines of that event loop. Unlike signal handlers
@@ -1343,7 +1345,8 @@ Executing code in thread or process pools
.. awaitablemethod:: loop.run_in_executor(executor, func, *args)
- Arrange for *func* to be called in the specified executor.
+ Arrange for *func* to be called in the specified executor
+ passing *args* as positional arguments.
The *executor* argument should be an :class:`concurrent.futures.Executor`
instance. The default executor is used if *executor* is ``None``.
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst
index 863b3e336572aa..e2a6752be12b67 100644
--- a/Doc/library/asyncio-task.rst
+++ b/Doc/library/asyncio-task.rst
@@ -557,7 +557,7 @@ Running Tasks Concurrently
provides stronger safety guarantees than *gather* for scheduling a nesting of subtasks:
if a task (or a subtask, a task scheduled by a task)
raises an exception, *TaskGroup* will, while *gather* will not,
- cancel the remaining scheduled tasks).
+ cancel the remaining scheduled tasks.
.. _asyncio_example_gather:
@@ -771,6 +771,9 @@ Timeouts
An :ref:`asynchronous context manager `
for cancelling overdue coroutines.
+ Prefer using :func:`asyncio.timeout` or :func:`asyncio.timeout_at`
+ rather than instantiating :class:`!Timeout` directly.
+
``when`` should be an absolute time at which the context should time out,
as measured by the event loop's clock:
diff --git a/Doc/library/atexit.rst b/Doc/library/atexit.rst
index 02d2f0807df8f6..b5caf5502d0e1c 100644
--- a/Doc/library/atexit.rst
+++ b/Doc/library/atexit.rst
@@ -4,14 +4,11 @@
.. module:: atexit
:synopsis: Register and execute cleanup functions.
-.. moduleauthor:: Skip Montanaro
-.. sectionauthor:: Skip Montanaro
-
--------------
-The :mod:`atexit` module defines functions to register and unregister cleanup
+The :mod:`!atexit` module defines functions to register and unregister cleanup
functions. Functions thus registered are automatically executed upon normal
-interpreter termination. :mod:`atexit` runs these functions in the *reverse*
+interpreter termination. :mod:`!atexit` runs these functions in the *reverse*
order in which they were registered; if you register ``A``, ``B``, and ``C``,
at interpreter termination time they will be run in the order ``C``, ``B``,
``A``.
@@ -64,7 +61,7 @@ a cleanup function is undefined.
Remove *func* from the list of functions to be run at interpreter shutdown.
:func:`unregister` silently does nothing if *func* was not previously
registered. If *func* has been registered more than once, every occurrence
- of that function in the :mod:`atexit` call stack will be removed. Equality
+ of that function in the :mod:`!atexit` call stack will be removed. Equality
comparisons (``==``) are used internally during unregistration, so function
references do not need to have matching identities.
@@ -72,14 +69,14 @@ a cleanup function is undefined.
.. seealso::
Module :mod:`readline`
- Useful example of :mod:`atexit` to read and write :mod:`readline` history
+ Useful example of :mod:`!atexit` to read and write :mod:`readline` history
files.
.. _atexit-example:
-:mod:`atexit` Example
----------------------
+:mod:`!atexit` Example
+----------------------
The following simple example demonstrates how a module can initialize a counter
from a file when it is imported and save the counter's updated value
diff --git a/Doc/library/base64.rst b/Doc/library/base64.rst
index 478686bc30035c..771628677c3d98 100644
--- a/Doc/library/base64.rst
+++ b/Doc/library/base64.rst
@@ -87,6 +87,9 @@ POST request.
If *ignorechars* is specified, it should be a :term:`bytes-like object`
containing characters to ignore from the input when *validate* is true.
+ If *ignorechars* contains the pad character ``'='``, the pad characters
+ presented before the end of the encoded data and the excess pad characters
+ will be ignored.
The default value of *validate* is ``True`` if *ignorechars* is specified,
``False`` otherwise.
@@ -102,10 +105,10 @@ POST request.
For more information about the strict base64 check, see :func:`binascii.a2b_base64`
- .. versionchanged:: next
+ .. versionchanged:: 3.15
Added the *ignorechars* parameter.
- .. deprecated:: next
+ .. deprecated:: 3.15
Accepting the ``+`` and ``/`` characters with an alternative alphabet
is now deprecated.
@@ -139,7 +142,7 @@ POST request.
``/`` in the standard Base64 alphabet, and return the decoded
:class:`bytes`.
- .. deprecated:: next
+ .. deprecated:: 3.15
Accepting the ``+`` and ``/`` characters is now deprecated.
@@ -244,8 +247,9 @@ Refer to the documentation of the individual functions for more information.
after at most every *wrapcol* characters.
If *wrapcol* is zero (default), do not insert any newlines.
- *pad* controls whether the input is padded to a multiple of 4
- before encoding. Note that the ``btoa`` implementation always pads.
+ If *pad* is true, the input is padded with ``b'\0'`` so its length is a
+ multiple of 4 bytes before encoding.
+ Note that the ``btoa`` implementation always pads.
*adobe* controls whether the encoded byte sequence is framed with ``<~``
and ``~>``, which is used by the Adobe implementation.
@@ -265,8 +269,9 @@ Refer to the documentation of the individual functions for more information.
*adobe* controls whether the input sequence is in Adobe Ascii85 format
(i.e. is framed with <~ and ~>).
- *ignorechars* should be a byte string containing characters to ignore
- from the input. This should only contain whitespace characters, and by
+ *ignorechars* should be a :term:`bytes-like object` containing characters
+ to ignore from the input.
+ This should only contain whitespace characters, and by
default contains all whitespace characters in ASCII.
.. versionadded:: 3.4
diff --git a/Doc/library/bdb.rst b/Doc/library/bdb.rst
index a3c6da7a6d686b..c8b48901901f98 100644
--- a/Doc/library/bdb.rst
+++ b/Doc/library/bdb.rst
@@ -8,7 +8,7 @@
--------------
-The :mod:`bdb` module handles basic debugger functions, like setting breakpoints
+The :mod:`!bdb` module handles basic debugger functions, like setting breakpoints
or managing execution via the debugger.
The following exception is defined:
@@ -18,7 +18,7 @@ The following exception is defined:
Exception raised by the :class:`Bdb` class for quitting the debugger.
-The :mod:`bdb` module also defines two classes:
+The :mod:`!bdb` module also defines two classes:
.. class:: Breakpoint(self, file, line, temporary=False, cond=None, funcname=None)
diff --git a/Doc/library/binascii.rst b/Doc/library/binascii.rst
index d9f0baedec85f2..8a241e51ebfee6 100644
--- a/Doc/library/binascii.rst
+++ b/Doc/library/binascii.rst
@@ -10,10 +10,10 @@
--------------
-The :mod:`binascii` module contains a number of methods to convert between
+The :mod:`!binascii` module contains a number of methods to convert between
binary and various ASCII-encoded binary representations. Normally, you will not
use these functions directly but use wrapper modules like
-:mod:`base64` instead. The :mod:`binascii` module contains
+:mod:`base64` instead. The :mod:`!binascii` module contains
low-level functions written in C for greater speed that are used by the
higher-level modules.
@@ -28,7 +28,7 @@ higher-level modules.
ASCII-only unicode strings are now accepted by the ``a2b_*`` functions.
-The :mod:`binascii` module defines the following functions:
+The :mod:`!binascii` module defines the following functions:
.. function:: a2b_uu(string)
@@ -56,6 +56,9 @@ The :mod:`binascii` module defines the following functions:
If *ignorechars* is specified, it should be a :term:`bytes-like object`
containing characters to ignore from the input when *strict_mode* is true.
+ If *ignorechars* contains the pad character ``'='``, the pad characters
+ presented before the end of the encoded data and the excess pad characters
+ will be ignored.
The default value of *strict_mode* is ``True`` if *ignorechars* is specified,
``False`` otherwise.
@@ -72,7 +75,7 @@ The :mod:`binascii` module defines the following functions:
.. versionchanged:: 3.11
Added the *strict_mode* parameter.
- .. versionchanged:: next
+ .. versionchanged:: 3.15
Added the *ignorechars* parameter.
@@ -95,6 +98,112 @@ The :mod:`binascii` module defines the following functions:
Added the *wrapcol* parameter.
+.. function:: a2b_ascii85(string, /, *, foldspaces=False, adobe=False, ignorechars=b"")
+
+ Convert Ascii85 data back to binary and return the binary data.
+
+ Valid Ascii85 data contains characters from the Ascii85 alphabet in groups
+ of five (except for the final group, which may have from two to five
+ characters). Each group encodes 32 bits of binary data in the range from
+ ``0`` to ``2 ** 32 - 1``, inclusive. The special character ``z`` is
+ accepted as a short form of the group ``!!!!!``, which encodes four
+ consecutive null bytes.
+
+ *foldspaces* is a flag that specifies whether the 'y' short sequence
+ should be accepted as shorthand for 4 consecutive spaces (ASCII 0x20).
+ This feature is not supported by the "standard" Ascii85 encoding.
+
+ *adobe* controls whether the input sequence is in Adobe Ascii85 format
+ (i.e. is framed with <~ and ~>).
+
+ *ignorechars* should be a :term:`bytes-like object` containing characters
+ to ignore from the input.
+ This should only contain whitespace characters.
+
+ Invalid Ascii85 data will raise :exc:`binascii.Error`.
+
+ .. versionadded:: 3.15
+
+
+.. function:: b2a_ascii85(data, /, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)
+
+ Convert binary data to a formatted sequence of ASCII characters in Ascii85
+ coding. The return value is the converted data.
+
+ *foldspaces* is an optional flag that uses the special short sequence 'y'
+ instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This
+ feature is not supported by the "standard" Ascii85 encoding.
+
+ If *wrapcol* is non-zero, insert a newline (``b'\n'``) character
+ after at most every *wrapcol* characters.
+ If *wrapcol* is zero (default), do not insert any newlines.
+
+ If *pad* is true, the input is padded with ``b'\0'`` so its length is a
+ multiple of 4 bytes before encoding.
+ Note that the ``btoa`` implementation always pads.
+
+ *adobe* controls whether the encoded byte sequence is framed with ``<~``
+ and ``~>``, which is used by the Adobe implementation.
+
+ .. versionadded:: 3.15
+
+
+.. function:: a2b_base85(string, /)
+
+ Convert Base85 data back to binary and return the binary data.
+ More than one line may be passed at a time.
+
+ Valid Base85 data contains characters from the Base85 alphabet in groups
+ of five (except for the final group, which may have from two to five
+ characters). Each group encodes 32 bits of binary data in the range from
+ ``0`` to ``2 ** 32 - 1``, inclusive.
+
+ Invalid Base85 data will raise :exc:`binascii.Error`.
+
+ .. versionadded:: 3.15
+
+
+.. function:: b2a_base85(data, /, *, pad=False)
+
+ Convert binary data to a line of ASCII characters in Base85 coding.
+ The return value is the converted line.
+
+ If *pad* is true, the input is padded with ``b'\0'`` so its length is a
+ multiple of 4 bytes before encoding.
+
+ .. versionadded:: 3.15
+
+
+.. function:: a2b_z85(string, /)
+
+ Convert Z85 data back to binary and return the binary data.
+ More than one line may be passed at a time.
+
+ Valid Z85 data contains characters from the Z85 alphabet in groups
+ of five (except for the final group, which may have from two to five
+ characters). Each group encodes 32 bits of binary data in the range from
+ ``0`` to ``2 ** 32 - 1``, inclusive.
+
+ See `Z85 specification `_ for more information.
+
+ Invalid Z85 data will raise :exc:`binascii.Error`.
+
+ .. versionadded:: 3.15
+
+
+.. function:: b2a_z85(data, /, *, pad=False)
+
+ Convert binary data to a line of ASCII characters in Z85 coding.
+ The return value is the converted line.
+
+ If *pad* is true, the input is padded with ``b'\0'`` so its length is a
+ multiple of 4 bytes before encoding.
+
+ See `Z85 specification `_ for more information.
+
+ .. versionadded:: 3.15
+
+
.. function:: a2b_qp(data, header=False)
Convert a block of quoted-printable data back to binary and return the binary
diff --git a/Doc/library/bisect.rst b/Doc/library/bisect.rst
index d5ec4212c1f9f4..2c29a5ec992737 100644
--- a/Doc/library/bisect.rst
+++ b/Doc/library/bisect.rst
@@ -3,9 +3,6 @@
.. module:: bisect
:synopsis: Array bisection algorithms for binary searching.
-.. sectionauthor:: Fred L. Drake, Jr.
-.. sectionauthor:: Raymond Hettinger
-.. example based on the PyModules FAQ entry by Aaron Watters
**Source code:** :source:`Lib/bisect.py`
@@ -16,7 +13,7 @@ having to sort the list after each insertion. For long lists of items with
expensive comparison operations, this can be an improvement over
linear searches or frequent resorting.
-The module is called :mod:`bisect` because it uses a basic bisection
+The module is called :mod:`!bisect` because it uses a basic bisection
algorithm to do its work. Unlike other bisection tools that search for a
specific value, the functions in this module are designed to locate an
insertion point. Accordingly, the functions never call an :meth:`~object.__eq__`
@@ -27,9 +24,9 @@ point between values in an array.
.. note::
The functions in this module are not thread-safe. If multiple threads
- concurrently use :mod:`bisect` functions on the same sequence, this
+ concurrently use :mod:`!bisect` functions on the same sequence, this
may result in undefined behaviour. Likewise, if the provided sequence
- is mutated by a different thread while a :mod:`bisect` function
+ is mutated by a different thread while a :mod:`!bisect` function
is operating on it, the result is undefined. For example, using
:py:func:`~bisect.insort_left` on the same list from multiple threads
may result in the list becoming unsorted.
@@ -203,9 +200,9 @@ example uses :py:func:`~bisect.bisect` to look up a letter grade for an exam sco
based on a set of ordered numeric breakpoints: 90 and up is an 'A', 80 to 89 is
a 'B', and so on::
- >>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
- ... i = bisect(breakpoints, score)
- ... return grades[i]
+ >>> def grade(score)
+ ... i = bisect([60, 70, 80, 90], score)
+ ... return "FDCBA"[i]
...
>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']
diff --git a/Doc/library/bz2.rst b/Doc/library/bz2.rst
index 12650861c0fb5d..6c20e9c94a3eae 100644
--- a/Doc/library/bz2.rst
+++ b/Doc/library/bz2.rst
@@ -4,11 +4,6 @@
.. module:: bz2
:synopsis: Interfaces for bzip2 compression and decompression.
-.. moduleauthor:: Gustavo Niemeyer
-.. moduleauthor:: Nadeem Vawda
-.. sectionauthor:: Gustavo Niemeyer