Skip to content

Commit deb8259

Browse files
committed
gh-158597: Omit declaration locations for shared lazy submodules
1 parent 1822ff5 commit deb8259

4 files changed

Lines changed: 61 additions & 16 deletions

File tree

‎Doc/whatsnew/3.15.rst‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -199,9 +199,10 @@ restructuring or conditional imports scattered throughout the codebase.
199199

200200
In the case where loading a lazily imported module fails (for example, if
201201
the module does not exist), Python raises the exception at the point of
202-
first use rather than at import time. The associated traceback includes both
203-
the location where the name was accessed and the original import statement,
204-
making it straightforward to diagnose and debug the failure.
202+
first use rather than at import time. The traceback shows the access and the
203+
import failure. It can also identify the original import statement. Python
204+
omits this extra location when an attribute access on a package triggers a
205+
submodule import, since several declarations can refer to the same submodule.
205206

206207
For cases where you want to enable lazy loading globally without modifying
207208
source code, Python provides the :option:`-X lazy_imports <-X>` command-line

‎Lib/test/test_lazy_import/__init__.py‎

Lines changed: 52 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,34 @@ def test_lazy_modules_tracks_lazy_imports(self):
862862
class ErrorHandlingTests(LazyImportTestCase):
863863
"""Tests for error handling during lazy import reification."""
864864

865+
def test_shared_submodule_omits_declaration(self):
866+
code = textwrap.dedent("""
867+
import traceback
868+
869+
namespaces = {'A': {}, 'B': {}, 'helper': {}}
870+
for name in 'AB':
871+
exec(compile('lazy import xml.missing', name + '.py', 'exec'),
872+
namespaces[name])
873+
exec('import xml', namespaces['helper'])
874+
875+
for namespace in namespaces.values():
876+
for _ in range(2):
877+
try:
878+
exec(compile('xml.missing', 'access.py', 'exec'),
879+
namespace)
880+
except ModuleNotFoundError as exc:
881+
assert exc.name == 'xml.missing', exc.name
882+
assert exc.__cause__ is None, exc.__cause__
883+
assert exc.__context__ is None, exc.__context__
884+
assert not getattr(exc, '__notes__', ()), exc.__notes__
885+
frames = traceback.extract_tb(exc.__traceback__)
886+
assert frames[-1].filename == 'access.py', frames
887+
assert frames[-1].lineno == 1, frames
888+
else:
889+
raise AssertionError('ModuleNotFoundError was not raised')
890+
""")
891+
assert_python_ok("-c", code)
892+
865893
def test_missing_lazy_submodule_raises_module_not_found_error(self):
866894
"""Accessing a nonexistent lazy submodule via parent attr raises ModuleNotFoundError."""
867895
code = textwrap.dedent("""
@@ -938,20 +966,33 @@ def test_missing_lazy_from_import_shows_chained_traceback(self):
938966
'test.test_lazy_import.data.broken_module_chained_context',
939967
'test.test_lazy_import.data.broken_module_chained_suppressed',
940968
))
941-
def test_chained_exception_import_shows_notes(self, name):
942-
"""Accessing missing attribute from lazy from-import should chain errors."""
969+
@support.subTests('aliased', (False, True))
970+
def test_chained_exception_import_preserves_chain(self, name, aliased):
971+
statement = f'lazy import {name}' + (' as target' if aliased else '')
972+
access = 'target' if aliased else name
943973
code = textwrap.dedent(f"""
944-
lazy import {name}
974+
{statement}
945975
946976
try:
947-
_ = {name}
977+
_ = {access}
948978
except ValueError as e:
949-
assert any(
950-
note.startswith("lazy import of '{name}' declared in ")
951-
for note in e.__notes__
952-
), e.__notes__
979+
assert str(e) == 'This module always fails to import', e
980+
notes = getattr(e, '__notes__', ())
981+
if {aliased!r}:
982+
assert any(
983+
note.startswith("lazy import of '{name}' declared in ")
984+
for note in notes
985+
), notes
986+
else:
987+
assert not notes, notes
988+
assert (e.__cause__ is not None) is {name.endswith('_cause')}
989+
assert (e.__context__ is not None) is {name.endswith('_context')}
990+
assert e.__suppress_context__ is {not name.endswith('_context')}
991+
original = e.__cause__ or e.__context__
992+
if original is not None:
993+
assert str(original) == 'Cause of failure', original
953994
else:
954-
raise AssertionError("ImportError was not raised")
995+
raise AssertionError("ValueError was not raised")
955996
""")
956997
assert_python_ok("-c", code)
957998

@@ -997,6 +1038,8 @@ def test_lazy_submodule_traceback_hides_importlib_frames(self):
9971038
assert [frame.name for frame in frames] == ["<module>", "<module>"], frames
9981039
assert frames[0].filename == "<string>", frames
9991040
assert frames[1].filename.endswith("broken_module.py"), frames
1041+
assert exc.__cause__ is None, exc.__cause__
1042+
assert not getattr(exc, '__notes__', ()), exc.__notes__
10001043
else:
10011044
raise AssertionError("ValueError was not raised")
10021045
""")
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Lazy imports no longer report a potentially incorrect declaration location
2+
when a package attribute triggers a submodule import. The traceback
3+
still shows the access and the import failure.

‎Objects/lazyimportobject.c‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -567,7 +567,8 @@ _PyImport_LoadLazyImportTstate(PyThreadState *tstate, PyObject *lazy_import)
567567
return lazy_import_resolve_impl(tstate, lazy_import, NULL);
568568
}
569569

570-
// Resolve a pending child as an aliased import, preserving its declaration.
570+
// Resolve a pending child as an aliased import. The shared source can belong
571+
// to another namespace, so leave the declaration location unset.
571572
PyObject *
572573
_PyLazyImport_LoadChild(PyThreadState *tstate, PyObject *declaration,
573574
PyObject *name)
@@ -596,9 +597,6 @@ _PyLazyImport_LoadChild(PyThreadState *tstate, PyObject *declaration,
596597
if (lz == NULL) {
597598
return NULL;
598599
}
599-
PyLazyImportObject *child = PyLazyImportObject_CAST(lz);
600-
child->lz_code = (PyCodeObject *)Py_XNewRef(source->lz_code);
601-
child->lz_instr_offset = source->lz_instr_offset;
602600
PyObject *result = _PyImport_LoadLazyImportTstate(tstate, lz);
603601
Py_DECREF(lz);
604602
if (result != NULL && PyModule_Check(result) &&

0 commit comments

Comments
 (0)