[3.14] gh-142763: Fix race in ZoneInfo cache eviction (gh-144978) (#145781)

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

(cherry picked from commit 665c1db94f)

Co-authored-by: Sam Gross <colesbury@gmail.com>
This commit is contained in:
Miss Islington (bot) 2026-03-10 20:39:40 +01:00 committed by GitHub
parent e7bc1526ca
commit 79051f8a07
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 7 additions and 1 deletions

View file

@ -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

View file

@ -0,0 +1,2 @@
Fix a race condition between :class:`zoneinfo.ZoneInfo` creation and
:func:`zoneinfo.ZoneInfo.clear_cache` that could raise :exc:`KeyError`.