Repository navigation
Conversation
Previously, taking the union of two concrete modules (e.g. `json if flag else pickle`) collapsed them into a bare `types.ModuleType` because `_remove_redundant_union_items` treated any `types.ModuleType` instance as a subtype of another and `make_simplified_union` then erased `extra_attrs`. Even when concrete module `extra_attrs` were retained, `analyze_member_var_access` still fell back to `types.ModuleType.__getattr__ -> Any`. This change: - Keeps distinct concrete modules (different `extra_attrs.mod_name`) separate in `_remove_redundant_union_items` while still deduplicating identical modules and simplifying unions with generic `types.ModuleType` (`extra_attrs is None`). - Includes `mod_name` in `ExtraAttrs.__eq__`/`__hash__` and `astdiff` snapshots. - Resolves attribute lookups (and module-level `__getattr__` / `Final` checks) against `extra_attrs` for concrete module instances instead of falling back to `types.ModuleType.__getattr__`. - Preserves explicit `types.ModuleType` annotations without narrowing in `binder.assign_type`, and handles concrete module meets and disambiguated module names in error messages. Fixes python#22302 Co-Authored-By: Claude Code <noreply@anthropic.com>
Contributor
|
Diff from mypy_primer, showing the effect of this PR on open source code: colour (https://github.com/colour-science/colour)
- colour/__init__.py:1028: error: Incompatible import of "colour" (imported name has type Module, local name has type "type[colour]") [assignment]
+ colour/__init__.py:1028: error: Incompatible import of "colour" (imported name has type Module "colour", local name has type "type[colour]") [assignment]
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #22302
Summary
Taking the union of two concrete modules (such as
mod = json if flag else pickle) previously collapsed the type to baretypes.ModuleType, losing all attribute and protocol checking.Root Cause
mypy/typeops.py(_remove_redundant_union_items), two concrete moduleInstances share the same nominalTypeInfo(types.ModuleType), sois_proper_subtypetreated the second module as redundant and dropped it;make_simplified_unionthen saw multiple distinctExtraAttrsand erasedextra_attrstoNone.extra_attrswere preserved on anInstance(e.g.,m1 if flag else m1or a union item),mypy/checkmember.py(analyze_member_var_access) fell back totypes.ModuleType.__getattr__ -> Anywhenevermx.module_symbol_tablewasNone, and skippeditype.extra_attrswhenmod_namewas set.Changes
mypy/typeops.py: Prevent_remove_redundant_union_itemsfrom treating one concrete module (extra_attrs.mod_name is not None) as a supertype of a different module or generictypes.ModuleType. Identical modules still deduplicate, unions with generictypes.ModuleType(extra_attrs is None) still simplify totypes.ModuleType, and non-moduleextra_attrs(hasattr/functools.partial) remain unchanged.mypy/types.py,mypy/server/astdiff.py: Includemod_nameinExtraAttrs.__hash__,ExtraAttrs.__eq__, andastdiffsnapshots so distinct modules with identical attribute maps are not conflated.mypy/checkmember.py: Skiptypes.ModuleType.__getattr__whenitype.extra_attrs.mod_nameis set; resolve attributes (includingFinalwrite checks and PEP 562 module-level__getattr__) fromitype.extra_attrswhile preserving symbol-table precedence for direct module expressions (e.g., cyclic definitions).mypy/checker.py,mypy/meet.py: Keepmod_nameintact duringhasattr()narrowing and returnUninhabitedType(orNoneTypewithout strict optional) when meeting two distinct concrete modules, enabling accuratehasattr()narrowing on unions of concrete modules.mypy/binder.py: Avoid narrowing variables explicitly annotated astypes.ModuleType(extra_attrs is None) to a concrete module on assignment, preserving explicit dynamictypes.ModuleTypeescape hatches.mypy/messages.py: Disambiguate distinct concrete modules asModule "<name>"viafind_type_overlapswhen multiple module types appear in the same diagnostic (e.g.,[union-attr]errors).test-data/unit/check-modules.test: Added regression tests covering unions of two concrete modules, common/missing/Finalattributes,hasattr()narrowing, same-module deduplication, empty modules, unions with generictypes.ModuleType,Protocolchecking, and module-level__getattr__.Verification
pytest -n 8 mypy/test/testcheck.py: 8363 passed, 16 skipped, 7 xfailedpytest -n 8 mypy/test/testsubtypes.py mypy/test/testfinegrained.py mypy/test/testdeps.py mypy/test/testdiff.py: 1093 passed, 27 skippedpytest -n 0 mypy/test/testsubtypes.py mypy/test/testtypes.py: 148 passed, 2 skippedpython -m mypy --config-file mypy_self_check.ini mypy: Success (0 issues in 195 source files)black --checkandruff checkon all modified files: passed🤖 Generated with Claude Code