diff --git a/mypy/checker.py b/mypy/checker.py index 3f2a8476ed934..aaea642d3cbaa 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -207,6 +207,7 @@ def __init__(self) -> None: WithStmt, YieldExpr, get_func_def, + get_member_expr_fullname, is_final_node, ) from mypy.operators import flip_ops, int_op_to_method, neg_ops @@ -2839,9 +2840,49 @@ def check__exit__return_type(self, defn: FuncItem) -> None: ): self.msg.incorrect__exit__return(defn) + def check_deferred_member_bases(self, defn: ClassDef) -> None: + """Validate base classes like ``obj.attr`` whose type was unknown in semanal.""" + for member, base_expr in defn.info.deferred_member_bases: + if member.type is None: + continue + typ = get_proper_type(member.type) + if isinstance(typ, PartialType): + continue + is_any_base = ( + isinstance(typ, AnyType) + or isinstance(typ, Instance) + and typ.type.fullname == "builtins.type" + or isinstance(typ, TypeType) + and isinstance(typ.item, AnyType) + ) + is_type_type = isinstance(typ, TypeType) + if is_any_base or is_type_type: + if is_any_base and self.options.disallow_subclassing_any: + self.fail( + f'Class cannot subclass "{base_expr.name}" (has type "Any")', base_expr + ) + continue + self.fail( + f'Variable "{member.fullname}" is not valid as a type', + base_expr, + code=codes.VALID_TYPE, + ) + self.note( + "See https://mypy.readthedocs.io/en/stable/common_issues.html" + "#variables-vs-type-aliases", + base_expr, + code=codes.VALID_TYPE, + ) + msg = "Invalid base class" + name = get_member_expr_fullname(base_expr) + if name: + msg += f' "{name}"' + self.fail(msg, base_expr) + def visit_class_def(self, defn: ClassDef) -> None: """Type check a class definition.""" typ = defn.info + self.check_deferred_member_bases(defn) for base in typ.mro[1:]: if base.is_final: self.fail(message_registry.CANNOT_INHERIT_FROM_FINAL.format(base.name), defn) diff --git a/mypy/constraints.py b/mypy/constraints.py index aa095316c234e..d4916ecb82d18 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -342,7 +342,9 @@ def _infer_constraints( # checkexpr.has_erased_component(). if not type_state.keep_unions and isinstance(template, UnionType): template = mypy.typeops.make_simplified_union(template.items, keep_erased=True) + unsimplified_actual: UnionType | None = None if not type_state.keep_unions and isinstance(actual, UnionType): + unsimplified_actual = actual actual = mypy.typeops.make_simplified_union(actual.items, keep_erased=True) # Ignore Any types from the type suggestion engine to avoid them @@ -428,13 +430,16 @@ def _infer_constraints( # We infer constraints eagerly -- try to find constraints for a type # variable if possible. This seems to help with some real-world # use cases. - return any_constraints( - [ - infer_constraints_if_possible(template, a_item, direction) - for a_item in actual.items - ], - eager=True, - ) + options = [ + infer_constraints_if_possible(template, a_item, direction) for a_item in actual.items + ] + if unsimplified_actual is not None: + options.extend( + _options_lost_by_simplification( + template, actual.items, options, unsimplified_actual.items + ) + ) + return any_constraints(options, eager=True) if direction == SUPERTYPE_OF and isinstance(template, UnionType): # When the template is a union, we are okay with leaving some # type variables indeterminate. This helps with some special @@ -476,6 +481,39 @@ def _unwrap_type_type(tp: TypeType | UnionType) -> ProperType: return UnionType.make_union([cast(TypeType, get_proper_type(o)).item for o in tp.items]) +def _options_lost_by_simplification( + template: ProperType, + simplified_items: Sequence[Type], + simplified_options: list[list[Constraint] | None], + original_items: Sequence[Type], +) -> list[list[Constraint] | None]: + """Find constraint options for union items removed during simplification. + + Simplification drops an item if it's a proper subtype of another item, but + subtyping isn't always transitive. For example, ``MutableSequence[str]`` is + a subtype of ``Hashable``, but ``list[str]`` is not, even though + ``list[str]`` is a subtype of ``MutableSequence[str]``. If the template only + matches the dropped item, add it back as an option. + """ + simplified_ids = {id(get_proper_type(item)) for item in simplified_items} + extra: list[list[Constraint] | None] = [] + for item in original_items: + proper_item = get_proper_type(item) + if id(proper_item) in simplified_ids or isinstance(proper_item, UnionType): + continue + absorbers = [ + option + for simplified_item, option in zip(simplified_items, simplified_options) + if mypy.subtypes.is_proper_subtype(item, simplified_item, keep_erased_types=True) + ] + if not absorbers or any(option is not None for option in absorbers): + continue + option = infer_constraints_if_possible(template, item, SUBTYPE_OF) + if option is not None: + extra.append(option) + return extra + + def infer_constraints_if_possible( template: Type, actual: Type, direction: int ) -> list[Constraint] | None: diff --git a/mypy/nodes.py b/mypy/nodes.py index 1dfd70267b06a..1e7251a01e923 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -3690,6 +3690,7 @@ class is generic then it will be a type constructor of higher kind. "type_object_type", "default_depends", "typeddict_data", + "deferred_member_bases", ) _fullname: str # Fully qualified name @@ -3927,6 +3928,10 @@ def __init__(self, names: SymbolTable, defn: ClassDef, module_name: str) -> None self.type_object_type = None self.default_depends = {} self.typeddict_data = None + # Base class expressions like ``obj.attr`` whose attribute type is not + # known during semantic analysis. The type checker validates them once + # the attribute type has been inferred. This is not serialized. + self.deferred_member_bases: list[tuple[Var, MemberExpr]] = [] def add_type_vars(self) -> None: self.has_type_var_tuple_type = False diff --git a/mypy/semanal.py b/mypy/semanal.py index c079a865af1de..a9621f42ac928 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -2032,7 +2032,7 @@ def analyze_class(self, defn: ClassDef) -> None: self.mark_incomplete(defn.name, defn) return - base_types, base_error = bases_result + base_types, base_error, deferred_member_bases = bases_result if any(isinstance(base, PlaceholderType) for base, _ in base_types): # We need to know the TypeInfo of each base to construct the MRO. Placeholder types # are okay in nested positions, since they can't affect the MRO. @@ -2067,6 +2067,7 @@ def analyze_class(self, defn: ClassDef) -> None: self.prepare_class_def(defn) self.setup_type_vars(defn, tvar_defs) defn.info.default_depends = default_depends + defn.info.deferred_member_bases = deferred_member_bases if base_error: defn.info.fallback_to_any = True if any_meta: @@ -2370,7 +2371,10 @@ class Foo(Bar, Generic[T]): ... ) removed.append(i) declared_tvars.extend(tvars) - if isinstance(base, UnboundType): + if isinstance(base, UnboundType) and not ( + isinstance(base_expr, MemberExpr) + and self.get_member_base_var(base_expr) is not None + ): sym = self.lookup_qualified(base.name, base) if sym is not None and sym.node is not None: if sym.node.fullname in PROTOCOL_NAMES and i not in removed: @@ -2421,7 +2425,9 @@ def analyze_class_typevar_declaration(self, base: Type) -> tuple[TypeVarLikeList if not isinstance(base, UnboundType): return None unbound = base - sym = self.lookup_qualified(unbound.name, unbound) + # This is only a speculative lookup for Generic/Protocol; undefined names + # are reported when the base classes are analyzed. + sym = self.lookup_qualified(unbound.name, unbound, suppress_errors=True) if sym is None or sym.node is None: return None if ( @@ -2497,6 +2503,12 @@ def get_all_bases_tvars( """Return all type variable references in bases.""" tvars: TypeVarLikeList = [] for i, base_expr in enumerate(base_type_exprs): + if ( + isinstance(base_expr, MemberExpr) + and self.get_member_base_var(base_expr) is not None + ): + # A value attribute like obj.attr cannot contain type variables. + continue if i not in removed: try: base = self.expr_to_unanalyzed_type(base_expr) @@ -2610,7 +2622,7 @@ def get_name_repr_of_expr(self, expr: Expression) -> str | None: def analyze_base_classes( self, cls_name: str, base_type_exprs: list[Expression] - ) -> tuple[list[tuple[ProperType, Expression]], bool] | None: + ) -> tuple[list[tuple[ProperType, Expression]], bool, list[tuple[Var, MemberExpr]]] | None: """Analyze base class types. Return None if some definition was incomplete. Otherwise, return a tuple @@ -2618,9 +2630,12 @@ def analyze_base_classes( * List of (analyzed type, original expression) tuples * Boolean indicating whether one of the bases had a semantic analysis error + * List of member expression bases whose attribute type is not known yet; + these are checked by the type checker """ is_error = False - bases = [] + bases: list[tuple[ProperType, Expression]] = [] + deferred_member_bases: list[tuple[Var, MemberExpr]] = [] for i, base_expr in enumerate(base_type_exprs): if ( isinstance(base_expr, RefExpr) @@ -2637,6 +2652,24 @@ def analyze_base_classes( # class Foo(TypedDict("Foo", {"a": int})): ... # CallExpr continue + if isinstance(base_expr, MemberExpr): + member = self.get_member_base_var(base_expr) + if member is not None: + member_type = get_proper_type(member.type) if member.type is not None else None + if member_type is None: + # The attribute type is inferred by the type checker. + deferred_member_bases.append((member, base_expr)) + bases.append((AnyType(TypeOfAny.special_form), base_expr)) + continue + if isinstance(member_type, AnyType) or ( + isinstance(member_type, Instance) + and member_type.type.fullname == "builtins.type" + ): + # The attribute is a type object. Treat it like a variable + # annotated with ``type``, which is accepted as a base class. + bases.append((AnyType(TypeOfAny.special_form), base_expr)) + continue + try: base = self.expr_to_analyzed_type( base_expr, @@ -2659,7 +2692,32 @@ def analyze_base_classes( return None base = get_proper_type(base) bases.append((base, base_expr)) - return bases, is_error + return bases, is_error, deferred_member_bases + + def get_member_base_var(self, expr: MemberExpr) -> Var | None: + """Return the attribute accessed by a base class expression like ``obj.attr``. + + Only attributes of statically known instances or class objects are + considered; these are the cases where the type of the base expression can + be determined by the type checker. + """ + if not isinstance(expr.expr, RefExpr): + return None + node = expr.expr.node + if isinstance(node, TypeInfo): + sym = node.get(expr.name) + elif isinstance(node, Var) and node.type is not None: + typ = get_proper_type(node.type) + if isinstance(typ, TypeType): + typ = typ.item + if not isinstance(typ, Instance): + return None + sym = typ.type.get(expr.name) + else: + return None + if sym is None or not isinstance(sym.node, Var): + return None + return sym.node def configure_base_classes( self, defn: ClassDef, bases: list[tuple[ProperType, Expression]] @@ -2682,7 +2740,11 @@ def configure_base_classes( self.fail('Cannot subclass "NewType"', defn) base_types.append(base) elif isinstance(base, AnyType): - if self.options.disallow_subclassing_any: + is_deferred = any( + deferred_expr is base_expr + for _, deferred_expr in defn.info.deferred_member_bases + ) + if self.options.disallow_subclassing_any and not is_deferred: if isinstance(base_expr, (NameExpr, MemberExpr)): msg = f'Class cannot subclass "{base_expr.name}" (has type "Any")' else: diff --git a/test-data/unit/check-classes.test b/test-data/unit/check-classes.test index a89a5f3690281..900840a6c0f4b 100644 --- a/test-data/unit/check-classes.test +++ b/test-data/unit/check-classes.test @@ -9848,3 +9848,34 @@ def f(x: int, y: int)-> int: ... fs = [lambda df, x: df.foo, f] reveal_type(fs) # N: Revealed type is "builtins.list[def (Any, Any) -> Any]" + +[case testSubclassMemberWithType] +# https://github.com/python/mypy/issues/22337 +class Person: + def __init__(self, name: str, age: int, characteristics: type) -> None: + self.name = name + self.age = age + self.characteristics = characteristics + +def foo(person: Person) -> None: + class Sub(person.characteristics): pass + class Sub2(Person.characteristics): pass + +[case testSubclassMemberWithNonType] +class Person: + def __init__(self, characteristics: int) -> None: + self.characteristics = characteristics + +def foo(person: Person) -> None: + class Sub(person.characteristics): pass # E: Variable "__main__.Person.characteristics" is not valid as a type \ + # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases \ + # E: Invalid base class "person.characteristics" + +[case testSubclassMemberWithTypeDisallowAny] +# flags: --disallow-subclassing-any +class Person: + def __init__(self, characteristics: type) -> None: + self.characteristics = characteristics + +def foo(person: Person) -> None: + class Sub(person.characteristics): pass # E: Class cannot subclass "characteristics" (has type "Any") diff --git a/test-data/unit/check-inference-context.test b/test-data/unit/check-inference-context.test index 53705ee43be16..ba49c04b5cea2 100644 --- a/test-data/unit/check-inference-context.test +++ b/test-data/unit/check-inference-context.test @@ -1680,3 +1680,17 @@ x: Union[B, C] fn: Callable[[Union[A, B]], None] fn = make(x) reveal_type(fn) # N: Revealed type is "def (__main__.B | __main__.C | __main__.A)" + +[case testListLiteralContextWithUnhashableListAndHashableSequence] +# https://github.com/python/mypy/issues/22342 +from typing import Hashable, MutableSequence + +def f(k: list[bool] | Hashable | MutableSequence[str]) -> None: ... + +f(["a", "b"]) +f([True]) +f([1.5]) # E: Argument 1 to "f" has incompatible type "list[float]"; expected "list[bool] | Hashable | MutableSequence[str]" \ + # N: Following member(s) of "list[float]" have conflicts: \ + # N: __hash__: expected "Callable[[], int]", got "None" +[builtins fixtures/list_hashable.pyi] +[typing fixtures/typing-full.pyi] diff --git a/test-data/unit/fixtures/list_hashable.pyi b/test-data/unit/fixtures/list_hashable.pyi new file mode 100644 index 0000000000000..acb6845e66814 --- /dev/null +++ b/test-data/unit/fixtures/list_hashable.pyi @@ -0,0 +1,43 @@ +# Builtins stub used in list tests that need hashability information. + +import types +from typing import Any, ClassVar, Generic, Iterable, Iterator, MutableSequence, TypeVar, overload + +T = TypeVar('T') + +class object: + def __init__(self) -> None: pass + def __eq__(self, other: object) -> bool: pass + def __hash__(self) -> int: pass + +class type: pass + +class list(MutableSequence[T]): + __hash__: ClassVar[None] # type: ignore[assignment] + @overload + def __init__(self) -> None: pass + @overload + def __init__(self, x: Iterable[T]) -> None: pass + def __iter__(self) -> Iterator[T]: pass + def __len__(self) -> int: pass + def __contains__(self, item: object) -> bool: pass + def __add__(self, x: list[T]) -> list[T]: pass + def __mul__(self, x: int) -> list[T]: pass + def __getitem__(self, x: Any) -> T: pass + def __setitem__(self, x: Any, v: T) -> None: pass + def append(self, x: T) -> None: pass + def extend(self, x: Iterable[T]) -> None: pass + +class tuple(Generic[T]): pass +class function: pass +class int: + def __bool__(self) -> bool: pass +class float: + def __bool__(self) -> bool: pass +class str: + def __len__(self) -> bool: pass +class bool(int): pass + +property = object() # Dummy definition. + +class dict: pass