https://github.com/python/cpython/commit/dd30f16ac0834aef9b3992e614ea3237c37ea71e
commit: dd30f16ac0834aef9b3992e614ea3237c37ea71e
branch: main
author: Kumar Aditya <[email protected]>
committer: kumaraditya303 <[email protected]>
date: 2026-02-09T13:20:35Z
summary:

gh-141563: make `PyDateTime_IMPORT` thread-safe (#144210)

files:
A 
Misc/NEWS.d/next/Core_and_Builtins/2026-02-02-17-07-34.gh-issue-141563.GheXjr.rst
M Include/datetime.h

diff --git a/Include/datetime.h b/Include/datetime.h
index ed36e6e48c87d2..ed7e55009d2208 100644
--- a/Include/datetime.h
+++ b/Include/datetime.h
@@ -196,8 +196,23 @@ typedef struct {
 /* Define global variable for the C API and a macro for setting it. */
 static PyDateTime_CAPI *PyDateTimeAPI = NULL;
 
-#define PyDateTime_IMPORT \
-    PyDateTimeAPI = (PyDateTime_CAPI 
*)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0)
+static inline PyDateTime_CAPI *
+_PyDateTime_IMPORT(void) {
+    PyDateTime_CAPI *val = _Py_atomic_load_ptr(&PyDateTimeAPI);
+    if (val == NULL) {
+        PyDateTime_CAPI *capi = (PyDateTime_CAPI *)PyCapsule_Import(
+            PyDateTime_CAPSULE_NAME, 0);
+        if (capi != NULL) {
+            /* if the compare exchange fails then in that case
+               another thread would have initialized it */
+            _Py_atomic_compare_exchange_ptr(&PyDateTimeAPI, &val, (void 
*)capi);
+            return capi;
+        }
+    }
+    return val;
+}
+
+#define PyDateTime_IMPORT _PyDateTime_IMPORT()
 
 /* Macro for access to the UTC singleton */
 #define PyDateTime_TimeZone_UTC PyDateTimeAPI->TimeZone_UTC
diff --git 
a/Misc/NEWS.d/next/Core_and_Builtins/2026-02-02-17-07-34.gh-issue-141563.GheXjr.rst
 
b/Misc/NEWS.d/next/Core_and_Builtins/2026-02-02-17-07-34.gh-issue-141563.GheXjr.rst
new file mode 100644
index 00000000000000..4059525f090c50
--- /dev/null
+++ 
b/Misc/NEWS.d/next/Core_and_Builtins/2026-02-02-17-07-34.gh-issue-141563.GheXjr.rst
@@ -0,0 +1 @@
+Fix thread safety of :c:macro:`! PyDateTime_IMPORT`.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to