From e0b87384ba0d32f18b722df5fe06e44c217d332b Mon Sep 17 00:00:00 2001 From: hauntsaninja Date: Thu, 10 Apr 2025 17:47:08 -0700 Subject: [PATCH] Fix incremental issue with namespace packages Fixes #12664 A root cause is there is this stateful `_update_ns_ancestors` thing in `modulefinder`, so if things get called in the wrong order, you can get incorrect results. See also the logic in `all_imported_modules_in_file` where we've fixed several bugs like this previously, like #13124 and #10937 As a result of (seemingly accidentally) reusing imports across modules, we can end up in a situation where the namespace gets added as a dependency to other modules and so on the cached run we attempt to find namespace before package, which does not work I am not sure this `imports` code path is even needed, so I will open an alternate PR. I can't write a good test for this because it requires something in site_packages, but here's a minimal repro: ``` set -eux rm -rf repro mkdir repro cd repro SITEPACK=env/site-packages mkdir -p $SITEPACK mkdir $SITEPACK/ruamel mkdir $SITEPACK/ruamel/yaml printf 'from ruamel.yaml.main import *' > $SITEPACK/ruamel/yaml/__init__.py printf 'import ruamel.yaml' > $SITEPACK/ruamel/yaml/main.py printf '' > $SITEPACK/ruamel/yaml/py.typed printf 'import ruamel.yaml' > a.py printf 'import a' > main.py rm -rf .mypy_cache PYTHONPATH=$SITEPACK mypy main.py PYTHONPATH=$SITEPACK mypy main.py ``` --- mypy/semanal_main.py | 1 + 1 file changed, 1 insertion(+) diff --git a/mypy/semanal_main.py b/mypy/semanal_main.py index 92a1c24b7b4c..545c131b1ba8 100644 --- a/mypy/semanal_main.py +++ b/mypy/semanal_main.py @@ -389,6 +389,7 @@ def semantic_analyze_target( analyzer.global_decls = [set()] analyzer.nonlocal_decls = [set()] analyzer.globals = tree.names + analyzer.imports = set() analyzer.progress = False with state.wrap_context(check_blockers=False): refresh_node = node