From 83210950efa9d986300ebdc257d305fa80d78b5f Mon Sep 17 00:00:00 2001 From: Jacob Walls Date: Sun, 9 Mar 2025 16:03:12 -0400 Subject: [PATCH] Avoid importing submodules sharing names with standard library modules --- ChangeLog | 2 ++ astroid/interpreter/_import/spec.py | 2 +- tests/test_modutils.py | 15 +++++++++++++++ tests/testdata/python3/data/divide_by_zero.py | 1 + 4 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 tests/testdata/python3/data/divide_by_zero.py diff --git a/ChangeLog b/ChangeLog index 54975c4d77..d730e8e829 100644 --- a/ChangeLog +++ b/ChangeLog @@ -37,7 +37,9 @@ What's New in astroid 3.3.10? ============================= Release date: TBA +* Avoid importing submodules sharing names with standard library modules. + Closes #2684 What's New in astroid 3.3.9? diff --git a/astroid/interpreter/_import/spec.py b/astroid/interpreter/_import/spec.py index 1e4073ecf6..9628f7453a 100644 --- a/astroid/interpreter/_import/spec.py +++ b/astroid/interpreter/_import/spec.py @@ -174,7 +174,7 @@ def find_module( # module. Note that `find_spec` actually imports parent modules, so we want to make # sure we only run this code for stuff that can be expected to be frozen. For now # this is only stdlib. - if modname in sys.stdlib_module_names or ( + if (modname in sys.stdlib_module_names and not processed) or ( processed and processed[0] in sys.stdlib_module_names ): try: diff --git a/tests/test_modutils.py b/tests/test_modutils.py index 6635ba186e..e1b4be3841 100644 --- a/tests/test_modutils.py +++ b/tests/test_modutils.py @@ -628,3 +628,18 @@ def test_find_setuptools_pep660_editable_install(): with unittest.mock.patch.object(sys, "meta_path", new=[_EditableFinder]): assert spec.find_spec(["example"]) assert spec.find_spec(["example", "subpackage"]) + + +def test_no_import_done_for_submodule_sharing_std_lib_name() -> None: + sys.path.insert(0, resources.find("data")) + try: + with pytest.raises(ImportError): + spec._find_spec_with_path( + [resources.find("data")], + "trace", + ("divide_by_zero", "trace"), + ("divide_by_zero",), + resources.find("data/divide_by_zero"), + ) + finally: + sys.path.pop(0) diff --git a/tests/testdata/python3/data/divide_by_zero.py b/tests/testdata/python3/data/divide_by_zero.py new file mode 100644 index 0000000000..72dca4d5e4 --- /dev/null +++ b/tests/testdata/python3/data/divide_by_zero.py @@ -0,0 +1 @@ +1 / 0