Skip to content
Closed
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
41 changes: 41 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
52 changes: 45 additions & 7 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions mypy/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
76 changes: 69 additions & 7 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -2610,17 +2622,20 @@ 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
with these items:

* 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)
Expand All @@ -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,
Expand All @@ -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]]
Expand All @@ -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:
Expand Down
31 changes: 31 additions & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -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")
14 changes: 14 additions & 0 deletions test-data/unit/check-inference-context.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]
43 changes: 43 additions & 0 deletions test-data/unit/fixtures/list_hashable.pyi
Original file line number Diff line number Diff line change
@@ -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
Loading