cpython/Lib/importlib
Gregory P. Smith c117ef1a1c
[3.13] gh-143650: Fix importlib race condition on import failure (GH-143651) (#144697)
gh-143650: Fix importlib race condition on import failure (GH-143651)

Fix a race condition where a thread could receive a partially-initialized
module when another thread's import fails. The race occurs when:

1. Thread 1 starts importing, adds module to sys.modules
2. Thread 2 sees the module in sys.modules via the fast path
3. Thread 1's import fails, removes module from sys.modules
4. Thread 2 returns a stale module reference not in sys.modules

The fix adds verification after the "skip lock" optimization in both Python
and C code paths to check if the module is still in sys.modules. If the
module was removed (due to import failure), we retry the import so the
caller receives the actual exception from the import failure rather than
a stale module reference.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

cherry picked from ac8b5b6890
2026-02-11 06:37:25 +00:00
..
metadata [3.13] gh-120910: Fix issue resolving relative paths outside site-packages. (GH-120911) (#120917) 2024-06-23 17:30:08 +00:00
resources [3.13] gh-123085: Fix issue in inferred caller when resource package has no source (GH-123102) (#124024) 2025-08-15 14:21:16 +00:00
__init__.py [3.13] gh-125519: Improve traceback if importlib.reload() is called with a non-module object (GH-125520) (#125768) 2024-10-21 08:28:32 +00:00
_abc.py gh-102515: Remove unused imports in the Lib/ directory (#102516) 2023-03-08 11:45:38 +00:00
_bootstrap.py [3.13] gh-143650: Fix importlib race condition on import failure (GH-143651) (#144697) 2026-02-11 06:37:25 +00:00
_bootstrap_external.py [3.13] gh-141930: Use the regular IO stack to write .pyc files for a better error message on failure (GH-141931) (#142023) 2025-12-01 23:23:07 +01:00
abc.py [3.13] gh-121279: Re-add prematurely removed import warnings to importlib.abc (#121281) 2024-07-03 11:06:20 +02:00
machinery.py gh-114099 - Add iOS framework loading machinery. (GH-116454) 2024-03-19 08:36:19 -04:00
readers.py bpo-46118: Move importlib.resources to its own package. (#30176) 2021-12-30 21:00:48 -05:00
simple.py bpo-46118: Move importlib.resources to its own package. (#30176) 2021-12-30 21:00:48 -05:00
util.py [3.13] gh-117983: Defer import of threading for lazy module loading (GH-120233) (GH-121349) 2024-07-03 21:14:42 +00:00