Skip to content

Commit 8e26b33

Browse files
committed
Fix bug in __import__ during Python shutdown
Issue #26637: The importlib module now emits an ImportError rather than a TypeError if __import__() is tried during the Python shutdown process but sys.path is already cleared (set to None).
1 parent 09f7cc8 commit 8e26b33

File tree

3 files changed

+459
-441
lines changed

3 files changed

+459
-441
lines changed

Lib/importlib/_bootstrap.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -878,13 +878,20 @@ def _find_spec_legacy(finder, name, path):
878878

879879
def _find_spec(name, path, target=None):
880880
"""Find a module's loader."""
881-
if sys.meta_path is not None and not sys.meta_path:
881+
meta_path = sys.meta_path
882+
if meta_path is None:
883+
# PyImport_Cleanup() is running or has been called.
884+
raise ImportError("sys.meta_path is None, Python is likely "
885+
"shutting down")
886+
887+
if not meta_path:
882888
_warnings.warn('sys.meta_path is empty', ImportWarning)
889+
883890
# We check sys.modules here for the reload case. While a passed-in
884891
# target will usually indicate a reload there is no guarantee, whereas
885892
# sys.modules provides one.
886893
is_reload = name in sys.modules
887-
for finder in sys.meta_path:
894+
for finder in meta_path:
888895
with _ImportLockContext():
889896
try:
890897
find_spec = finder.find_spec

Misc/NEWS

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,11 @@ Core and Builtins
232232
Library
233233
-------
234234

235+
- Issue #26637: The :mod:`importlib` module now emits an :exc:`ImportError`
236+
rather than a :exc:`TypeError` if :func:`__import__` is tried during the
237+
Python shutdown process but :data:`sys.path` is already cleared (set to
238+
``None``).
239+
235240
- Issue #21925: :func:`warnings.formatwarning` now catches exceptions when
236241
calling :func;`linecache.getline` and
237242
:func:`tracemalloc.get_object_traceback` to be able to log

0 commit comments

Comments
 (0)