From 087d9a17de4746c57f9dae9dae6be9f6c34809d5 Mon Sep 17 00:00:00 2001 From: semanym <133956547+semanym@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:44:57 +0800 Subject: [PATCH] Preserve concrete module extra_attrs in unions 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 #22302 Co-Authored-By: Claude Code --- mypy/binder.py | 8 ++- mypy/checker.py | 14 +---- mypy/checkmember.py | 36 +++++++++-- mypy/meet.py | 6 ++ mypy/messages.py | 23 ++++++- mypy/server/astdiff.py | 1 + mypy/typeops.py | 14 +++++ mypy/types.py | 8 ++- test-data/unit/check-modules.test | 99 +++++++++++++++++++++++++++++++ 9 files changed, 185 insertions(+), 24 deletions(-) diff --git a/mypy/binder.py b/mypy/binder.py index 9984781733cd4..3355a8b0cacd3 100644 --- a/mypy/binder.py +++ b/mypy/binder.py @@ -526,9 +526,13 @@ def assign_type(self, expr: Expression, type: Type, declared_type: Type | None) self.put(expr, declared_type) else: self.put(expr, declared_type) - elif isinstance(p_declared, AnyType): + elif isinstance(p_declared, AnyType) or ( + isinstance(p_declared, Instance) + and p_declared.type.fullname == "types.ModuleType" + and p_declared.extra_attrs is None + ): # Mirroring the first case above, we don't narrow to a precise type if the variable - # has an explicit `Any` type annotation. + # has an explicit `Any` or `types.ModuleType` type annotation. if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred: self.put(expr, type) else: diff --git a/mypy/checker.py b/mypy/checker.py index ea7adc757d1d3..30386ece11be1 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -8529,13 +8529,7 @@ def add_any_attribute_to_type(self, typ: Type, name: str) -> Type: typ = get_proper_type(typ) any_type = AnyType(TypeOfAny.unannotated) if isinstance(typ, Instance): - result = typ.copy_with_extra_attr(name, any_type) - # For instances, we erase the possible module name, so that restrictions - # become anonymous types.ModuleType instances, allowing hasattr() to - # have effect on modules. - assert result.extra_attrs is not None - result.extra_attrs.mod_name = None - return result + return typ.copy_with_extra_attr(name, any_type) if isinstance(typ, TupleType): fallback = typ.partial_fallback.copy_with_extra_attr(name, any_type) return typ.copy_modified(fallback=fallback) @@ -8599,11 +8593,6 @@ def has_valid_attribute(self, typ: Type, name: str) -> bool: p_typ = get_proper_type(typ) if isinstance(p_typ, AnyType): return False - if isinstance(p_typ, Instance) and p_typ.extra_attrs and p_typ.extra_attrs.mod_name: - # Presence of module_symbol_table means this check will skip ModuleType.__getattr__ - module_symbol_table = p_typ.type.names - else: - module_symbol_table = None with self.msg.filter_errors() as watcher: analyze_member_access( name, @@ -8616,7 +8605,6 @@ def has_valid_attribute(self, typ: Type, name: str) -> bool: chk=self, # This is not a real attribute lookup so don't mess with deferring nodes. no_deferral=True, - module_symbol_table=module_symbol_table, ) return not watcher.has_new_errors() diff --git a/mypy/checkmember.py b/mypy/checkmember.py index e01d1e6a85790..0c0073f6aa8f1 100644 --- a/mypy/checkmember.py +++ b/mypy/checkmember.py @@ -584,10 +584,11 @@ def analyze_member_var_access( and name not in ["__getattr__", "__setattr__", "__getattribute__"] and not mx.is_operator and mx.module_symbol_table is None + and not (itype.extra_attrs and itype.extra_attrs.mod_name) ): # Above we skip ModuleType.__getattr__ etc. if we have a - # module symbol table, since the symbol table allows precise - # checking. + # module symbol table or concrete module extra_attrs, since they + # allow precise checking. if not mx.is_lvalue: for method_name in ("__getattribute__", "__getattr__"): method = info.get_method(method_name) @@ -638,10 +639,35 @@ def analyze_member_var_access( return AnyType(TypeOfAny.special_form) # Could not find the member. - if itype.extra_attrs and name in itype.extra_attrs.attrs: - # For modules use direct symbol table lookup. - if not itype.extra_attrs.mod_name: + if itype.extra_attrs: + # For direct module expressions (module_symbol_table is set), skip names + # already present in the symbol table (e.g. unresolved cyclic definitions) + # while still honoring attributes injected by hasattr(). + if name in itype.extra_attrs.attrs and ( + mx.module_symbol_table is None or name not in mx.module_symbol_table + ): + if ( + mx.is_lvalue + and not mx.chk.get_final_context() + and name in itype.extra_attrs.immutable + ): + mx.msg.cant_assign_to_final(name, attr_assign=True, ctx=mx.context) return itype.extra_attrs.attrs[name] + if ( + itype.extra_attrs.mod_name + and mx.module_symbol_table is None + and not mx.is_lvalue + and name not in ["__getattr__", "__setattr__", "__getattribute__"] + and not mx.is_operator + and "__getattr__" in itype.extra_attrs.attrs + ): + getattr_type = get_proper_type(itype.extra_attrs.attrs["__getattr__"]) + if isinstance(getattr_type, CallableType): + return getattr_type.ret_type + if isinstance(getattr_type, Overloaded): + return make_simplified_union([item.ret_type for item in getattr_type.items]) + if isinstance(getattr_type, AnyType): + return getattr_type if mx.is_super and not mx.suppress_errors: mx.msg.undefined_in_superclass(name, mx.context) diff --git a/mypy/meet.py b/mypy/meet.py index 0ca4dfabc73cb..5bae8e46137b4 100644 --- a/mypy/meet.py +++ b/mypy/meet.py @@ -88,6 +88,12 @@ def meet_types(s: Type, t: Type) -> ProperType: # the below subtype check, so that extra_attrs will not get erased. if (s.extra_attrs or t.extra_attrs) and is_same_type(s, t): if s.extra_attrs and t.extra_attrs: + if ( + s.extra_attrs.mod_name + and t.extra_attrs.mod_name + and s.extra_attrs.mod_name != t.extra_attrs.mod_name + ): + return UninhabitedType() if state.strict_optional else NoneType() if len(s.extra_attrs.attrs) > len(t.extra_attrs.attrs): # Return the one that has more precise information. return s diff --git a/mypy/messages.py b/mypy/messages.py index 1ef5dea68e2b5..55a28362f7633 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -2728,7 +2728,17 @@ def format_literal_value(typ: LiteralType) -> str: if itype.type.fullname == "types.ModuleType": # Make some common error messages simpler and tidier. base_str = "Module" - if itype.extra_attrs and itype.extra_attrs.mod_name and module_names: + if ( + itype.extra_attrs + and itype.extra_attrs.mod_name + and ( + module_names + or ( + fullnames is not None + and f"{itype.type.fullname}:{itype.extra_attrs.mod_name}" in fullnames + ) + ) + ): return f'{base_str} "{itype.extra_attrs.mod_name}"' return base_str if itype.type.fullname == "typing._SpecialForm": @@ -2951,7 +2961,16 @@ def find_type_overlaps(*types: Type) -> set[str]: for type in types: for t in collect_all_named_types(type): if isinstance(t, ProperType) and isinstance(t, Instance): - d.setdefault(t.type.name, set()).add(t.type.fullname) + if ( + t.type.fullname == "types.ModuleType" + and t.extra_attrs + and t.extra_attrs.mod_name + ): + d.setdefault(t.type.name, set()).add( + f"{t.type.fullname}:{t.extra_attrs.mod_name}" + ) + else: + d.setdefault(t.type.name, set()).add(t.type.fullname) elif isinstance(t, TypeAliasType) and t.alias: d.setdefault(t.alias.name, set()).add(t.alias.fullname) else: diff --git a/mypy/server/astdiff.py b/mypy/server/astdiff.py index 7b7a3d6c84564..193e3160beeb5 100644 --- a/mypy/server/astdiff.py +++ b/mypy/server/astdiff.py @@ -402,6 +402,7 @@ def visit_instance(self, typ: Instance) -> SnapshotItem: extra_attrs = ( tuple(sorted((k, v.accept(self)) for k, v in typ.extra_attrs.attrs.items())), tuple(typ.extra_attrs.immutable), + encode_optional_str(typ.extra_attrs.mod_name), ) else: extra_attrs = () diff --git a/mypy/typeops.py b/mypy/typeops.py index 8c53d250b576a..936d5a344e3c9 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -822,6 +822,20 @@ def _remove_redundant_union_items(items: list[Type], keep_erased: bool) -> list[ ): continue + # If tj is a concrete module (Instance with extra_attrs.mod_name), do not + # remove proper_ti unless it refers to the same module. + if ( + isinstance(proper_tj, Instance) + and proper_tj.extra_attrs is not None + and proper_tj.extra_attrs.mod_name is not None + and not ( + isinstance(proper_ti, Instance) + and proper_ti.extra_attrs is not None + and proper_tj.extra_attrs.mod_name == proper_ti.extra_attrs.mod_name + ) + ): + continue + if is_proper_subtype( ti, tj, keep_erased_types=keep_erased, ignore_promotions=True ): diff --git a/mypy/types.py b/mypy/types.py index f46e7b5491611..d37e0f6dae8d9 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -1594,12 +1594,16 @@ def __init__( self.mod_name = mod_name def __hash__(self) -> int: - return hash((tuple(self.attrs.items()), tuple(sorted(self.immutable)))) + return hash((tuple(self.attrs.items()), tuple(sorted(self.immutable)), self.mod_name)) def __eq__(self, other: object) -> bool: if not isinstance(other, ExtraAttrs): return NotImplemented - return self.attrs == other.attrs and self.immutable == other.immutable + return ( + self.attrs == other.attrs + and self.immutable == other.immutable + and self.mod_name == other.mod_name + ) def copy(self) -> ExtraAttrs: return ExtraAttrs(self.attrs.copy(), self.immutable.copy(), self.mod_name) diff --git a/test-data/unit/check-modules.test b/test-data/unit/check-modules.test index 5fba65f276a43..198e8aaa0200c 100644 --- a/test-data/unit/check-modules.test +++ b/test-data/unit/check-modules.test @@ -3254,3 +3254,102 @@ tmp/a.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#mi [out2] tmp/a.py:1: error: Cannot find implementation or library stub for module named "b" tmp/a.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports + +[case testUnionOfTwoConcreteModules] +import m1 +import m2 +import empty1 +import empty2 +import types + +def f(flag: bool) -> None: + mod = m1 if flag else m2 + reveal_type(mod) # N: Revealed type is "types.ModuleType | types.ModuleType" + reveal_type(mod.common) # N: Revealed type is "builtins.int | builtins.str" + reveal_type(mod.dumps) # N: Revealed type is "(def (obj: builtins.object) -> builtins.str) | (def (obj: builtins.object) -> builtins.int)" + reveal_type(mod.__file__) # N: Revealed type is "builtins.str" + mod.only_m1 # E: Item Module "m2" of Module "m1" | Module "m2" has no attribute "only_m1" + mod.does_not_exist # E: Item Module "m1" of Module "m1" | Module "m2" has no attribute "does_not_exist" \ + # E: Item Module "m2" of Module "m1" | Module "m2" has no attribute "does_not_exist" + mod.CONST = 1 # E: Cannot assign to final attribute "CONST" + + if hasattr(mod, "only_m1"): + reveal_type(mod.only_m1) # N: Revealed type is "builtins.int | Any" + mod.does_not_exist # E: Item Module "m1" of Module "m1" | Module "m2" has no attribute "does_not_exist" \ + # E: Item Module "m2" of Module "m1" | Module "m2" has no attribute "does_not_exist" + else: + reveal_type(mod) # N: Revealed type is "types.ModuleType" + reveal_type(mod.common) # N: Revealed type is "builtins.str" + mod.only_m1 # E: Module has no attribute "only_m1" + +def g(flag: bool) -> None: + same = m1 if flag else m1 + reveal_type(same) # N: Revealed type is "types.ModuleType" + reveal_type(same.common) # N: Revealed type is "builtins.int" + same.does_not_exist # E: Module has no attribute "does_not_exist" + + empties = empty1 if flag else empty2 + reveal_type(empties) # N: Revealed type is "types.ModuleType | types.ModuleType" + empties.foo # E: Item Module "empty1" of Module "empty1" | Module "empty2" has no attribute "foo" \ + # E: Item Module "empty2" of Module "empty1" | Module "empty2" has no attribute "foo" + +def h(flag: bool, generic_mod: types.ModuleType) -> None: + mixed1 = m1 if flag else generic_mod + reveal_type(mixed1) # N: Revealed type is "types.ModuleType" + reveal_type(mixed1.anything) # N: Revealed type is "Any" + + mixed2 = generic_mod if flag else m1 + reveal_type(mixed2) # N: Revealed type is "types.ModuleType" + reveal_type(mixed2.anything) # N: Revealed type is "Any" + +[file m1.py] +from typing import Final +common: int +only_m1: int +CONST: Final = 1 +def dumps(obj: object) -> str: ... +[file m2.py] +from typing import Final +common: str +only_m2: str +CONST: Final = 2 +def dumps(obj: object) -> int: ... +[file empty1.py] +[file empty2.py] +[builtins fixtures/module.pyi] + +[case testUnionOfConcreteModulesProtocolAndGetattr] +from typing import Protocol +import m1 +import m2 +import dyn + +class Dumper(Protocol): + def dumps(self, obj: object) -> str | int: ... + +class StrictDumper(Protocol): + def dumps(self, obj: object) -> str: ... + +def use_dumper(d: Dumper) -> None: ... +def use_strict(d: StrictDumper) -> None: ... + +def f(flag: bool) -> None: + mod = m1 if flag else m2 + use_dumper(mod) + use_strict(mod) # E: Argument 1 to "use_strict" has incompatible type Module "m1" | Module "m2"; expected "StrictDumper" + + mod_dyn = m1 if flag else dyn + reveal_type(mod_dyn.common) # N: Revealed type is "builtins.int | builtins.str" + reveal_type(mod_dyn.only_m1) # N: Revealed type is "builtins.int | builtins.str" + mod_dyn.missing # E: Item Module "m1" of Module "m1" | Module "dyn" has no attribute "missing" + +[file m1.py] +common: int +only_m1: int +def dumps(obj: object) -> str: ... +[file m2.py] +common: str +def dumps(obj: object) -> int: ... +[file dyn.py] +def __getattr__(name: str) -> str: ... +[builtins fixtures/module.pyi]