diff --git a/Doc/whatsnew/3.15.rst b/Doc/whatsnew/3.15.rst index b07c94287bdee6..9bea97ca26e17c 100644 --- a/Doc/whatsnew/3.15.rst +++ b/Doc/whatsnew/3.15.rst @@ -199,9 +199,10 @@ restructuring or conditional imports scattered throughout the codebase. In the case where loading a lazily imported module fails (for example, if the module does not exist), Python raises the exception at the point of -first use rather than at import time. The associated traceback includes both -the location where the name was accessed and the original import statement, -making it straightforward to diagnose and debug the failure. +first use rather than at import time. The traceback shows the access and the +import failure. It can also identify the original import statement. Python +omits this extra location when an attribute access on a package triggers a +submodule import, since several declarations can refer to the same submodule. For cases where you want to enable lazy loading globally without modifying source code, Python provides the :option:`-X lazy_imports <-X>` command-line diff --git a/Lib/test/test_lazy_import/__init__.py b/Lib/test/test_lazy_import/__init__.py index 6dd2f7c825e5dd..af806166cc7e81 100644 --- a/Lib/test/test_lazy_import/__init__.py +++ b/Lib/test/test_lazy_import/__init__.py @@ -862,6 +862,34 @@ def test_lazy_modules_tracks_lazy_imports(self): class ErrorHandlingTests(LazyImportTestCase): """Tests for error handling during lazy import reification.""" + def test_shared_submodule_omits_declaration(self): + code = textwrap.dedent(""" + import traceback + + namespaces = {'A': {}, 'B': {}, 'helper': {}} + for name in 'AB': + exec(compile('lazy import xml.missing', name + '.py', 'exec'), + namespaces[name]) + exec('import xml', namespaces['helper']) + + for namespace in namespaces.values(): + for _ in range(2): + try: + exec(compile('xml.missing', 'access.py', 'exec'), + namespace) + except ModuleNotFoundError as exc: + assert exc.name == 'xml.missing', exc.name + assert exc.__cause__ is None, exc.__cause__ + assert exc.__context__ is None, exc.__context__ + assert not getattr(exc, '__notes__', ()), exc.__notes__ + frames = traceback.extract_tb(exc.__traceback__) + assert frames[-1].filename == 'access.py', frames + assert frames[-1].lineno == 1, frames + else: + raise AssertionError('ModuleNotFoundError was not raised') + """) + assert_python_ok("-c", code) + def test_missing_lazy_submodule_raises_module_not_found_error(self): """Accessing a nonexistent lazy submodule via parent attr raises ModuleNotFoundError.""" code = textwrap.dedent(""" @@ -938,20 +966,33 @@ def test_missing_lazy_from_import_shows_chained_traceback(self): 'test.test_lazy_import.data.broken_module_chained_context', 'test.test_lazy_import.data.broken_module_chained_suppressed', )) - def test_chained_exception_import_shows_notes(self, name): - """Accessing missing attribute from lazy from-import should chain errors.""" + @support.subTests('aliased', (False, True)) + def test_chained_exception_import_preserves_chain(self, name, aliased): + statement = f'lazy import {name}' + (' as target' if aliased else '') + access = 'target' if aliased else name code = textwrap.dedent(f""" - lazy import {name} + {statement} try: - _ = {name} + _ = {access} except ValueError as e: - assert any( - note.startswith("lazy import of '{name}' declared in ") - for note in e.__notes__ - ), e.__notes__ + assert str(e) == 'This module always fails to import', e + notes = getattr(e, '__notes__', ()) + if {aliased!r}: + assert any( + note.startswith("lazy import of '{name}' declared in ") + for note in notes + ), notes + else: + assert not notes, notes + assert (e.__cause__ is not None) is {name.endswith('_cause')} + assert (e.__context__ is not None) is {name.endswith('_context')} + assert e.__suppress_context__ is {not name.endswith('_context')} + original = e.__cause__ or e.__context__ + if original is not None: + assert str(original) == 'Cause of failure', original else: - raise AssertionError("ImportError was not raised") + raise AssertionError("ValueError was not raised") """) assert_python_ok("-c", code) @@ -997,6 +1038,8 @@ def test_lazy_submodule_traceback_hides_importlib_frames(self): assert [frame.name for frame in frames] == ["", ""], frames assert frames[0].filename == "", frames assert frames[1].filename.endswith("broken_module.py"), frames + assert exc.__cause__ is None, exc.__cause__ + assert not getattr(exc, '__notes__', ()), exc.__notes__ else: raise AssertionError("ValueError was not raised") """) diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-12-00-00.gh-issue-158597.hX7mQp.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-12-00-00.gh-issue-158597.hX7mQp.rst new file mode 100644 index 00000000000000..73f1bd2fa4f9fe --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-21-12-00-00.gh-issue-158597.hX7mQp.rst @@ -0,0 +1,3 @@ +Lazy imports no longer report a potentially incorrect declaration location +when a package attribute triggers a submodule import. The traceback +still shows the access and the import failure. diff --git a/Objects/lazyimportobject.c b/Objects/lazyimportobject.c index aafd2ce764a1cb..2be1ce8b941040 100644 --- a/Objects/lazyimportobject.c +++ b/Objects/lazyimportobject.c @@ -567,7 +567,8 @@ _PyImport_LoadLazyImportTstate(PyThreadState *tstate, PyObject *lazy_import) return lazy_import_resolve_impl(tstate, lazy_import, NULL); } -// Resolve a pending child as an aliased import, preserving its declaration. +// Resolve a pending child as an aliased import. The shared source can belong +// to another namespace, so leave the declaration location unset. PyObject * _PyLazyImport_LoadChild(PyThreadState *tstate, PyObject *declaration, PyObject *name) @@ -596,9 +597,6 @@ _PyLazyImport_LoadChild(PyThreadState *tstate, PyObject *declaration, if (lz == NULL) { return NULL; } - PyLazyImportObject *child = PyLazyImportObject_CAST(lz); - child->lz_code = (PyCodeObject *)Py_XNewRef(source->lz_code); - child->lz_instr_offset = source->lz_instr_offset; PyObject *result = _PyImport_LoadLazyImportTstate(tstate, lz); Py_DECREF(lz); if (result != NULL && PyModule_Check(result) &&