Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions mypy/binder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
14 changes: 1 addition & 13 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand All @@ -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()

Expand Down
36 changes: 31 additions & 5 deletions mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions mypy/meet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 21 additions & 2 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions mypy/server/astdiff.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ()
Expand Down
14 changes: 14 additions & 0 deletions mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
):
Expand Down
8 changes: 6 additions & 2 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
99 changes: 99 additions & 0 deletions test-data/unit/check-modules.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Loading