https://github.com/python/cpython/commit/665c1db94f46f8e1a18a8c2f89adb3bc72cb83dc
commit: 665c1db94f46f8e1a18a8c2f89adb3bc72cb83dc
branch: main
author: Sam Gross <[email protected]>
committer: colesbury <[email protected]>
date: 2026-03-10T14:47:58-04:00
summary:

gh-142763: Fix race in ZoneInfo cache eviction (gh-144978)

The cache may be cleared between the evaluation of the if statement and the
call to popitem.

files:
A Misc/NEWS.d/next/Library/2025-12-18-00-00-00.gh-issue-142763.AJpZPVG5.rst
M Lib/zoneinfo/_zoneinfo.py

diff --git a/Lib/zoneinfo/_zoneinfo.py b/Lib/zoneinfo/_zoneinfo.py
index 3ffdb4c837192b..bd3fefc6c9d959 100644
--- a/Lib/zoneinfo/_zoneinfo.py
+++ b/Lib/zoneinfo/_zoneinfo.py
@@ -47,7 +47,11 @@ def __new__(cls, key):
         cls._strong_cache[key] = cls._strong_cache.pop(key, instance)
 
         if len(cls._strong_cache) > cls._strong_cache_size:
-            cls._strong_cache.popitem(last=False)
+            try:
+                cls._strong_cache.popitem(last=False)
+            except KeyError:
+                # another thread may have already emptied the cache
+                pass
 
         return instance
 
diff --git 
a/Misc/NEWS.d/next/Library/2025-12-18-00-00-00.gh-issue-142763.AJpZPVG5.rst 
b/Misc/NEWS.d/next/Library/2025-12-18-00-00-00.gh-issue-142763.AJpZPVG5.rst
new file mode 100644
index 00000000000000..a5330365e3e42e
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2025-12-18-00-00-00.gh-issue-142763.AJpZPVG5.rst
@@ -0,0 +1,2 @@
+Fix a race condition between :class:`zoneinfo.ZoneInfo` creation and
+:func:`zoneinfo.ZoneInfo.clear_cache` that could raise :exc:`KeyError`.

_______________________________________________
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