Skip to content

gh-130094: Fix race conditions in importlib #130101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions Lib/importlib/_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -1244,6 +1244,9 @@ def _find_spec(name, path, target=None):
raise ImportError("sys.meta_path is None, Python is likely "
"shutting down")

# gh-130094: Copy sys.meta_path so that we have a consistent view of the
# list while iterating over it.
meta_path = list(meta_path)
if not meta_path:
_warnings.warn('sys.meta_path is empty', ImportWarning)

Expand Down Expand Up @@ -1298,7 +1301,6 @@ def _sanity_check(name, package, level):


_ERR_MSG_PREFIX = 'No module named '
_ERR_MSG = _ERR_MSG_PREFIX + '{!r}'

def _find_and_load_unlocked(name, import_):
path = None
Expand All @@ -1308,15 +1310,22 @@ def _find_and_load_unlocked(name, import_):
if parent not in sys.modules:
_call_with_frames_removed(import_, parent)
# Crazy side-effects!
if name in sys.modules:
return sys.modules[name]
module = sys.modules.get(name)
if module is not None:
return module
parent_module = sys.modules[parent]
try:
path = parent_module.__path__
except AttributeError:
msg = f'{_ERR_MSG_PREFIX}{name!r}; {parent!r} is not a package'
raise ModuleNotFoundError(msg, name=name) from None
parent_spec = parent_module.__spec__
if getattr(parent_spec, '_initializing', False):
_call_with_frames_removed(import_, parent)
# Crazy side-effects (again)!
module = sys.modules.get(name)
if module is not None:
return module
child = name.rpartition('.')[2]
spec = _find_spec(name, path)
if spec is None:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix two race conditions involving concurrent imports that could lead to
spurious failures with :exc:`ModuleNotFoundError`.
Loading