From 8a02ccb2b9ae926f5c5ba77b2ca46a912e3243bb Mon Sep 17 00:00:00 2001 From: Sudhakar Date: Wed, 4 Nov 2026 10:23:30 +0530 Subject: [PATCH 1/5] Fix subclassing member with type and list literal context false positive Fix two mypy false positives: 1. Allow subclassing a base class that is a member access (obj.attr) when the attribute has type type (or Any). Previously mypy rejected it even though pyright accepts it. Deferred member bases are validated by the type checker after the attribute type is known. Fixes #22337. 2. When inferring constraints for a union actual type, do not drop options for items removed by union simplification. In particular, keep MutableSequence[str]'s option when list[bool] | Hashable | MutableSequence[str] is simplified to list[bool] | Hashable, so f(["a", "b"]) is not reported as an invalid list[bool]. Fixes #22342. --- mypy/checker.py | 40 ++++++++ mypy/constraints.py | 52 ++++++++-- mypy/nodes.py | 17 ++-- mypy/semanal.py | 101 ++++++++++++++++---- test-data/unit/check-classes.test | 31 ++++++ test-data/unit/check-inference-context.test | 14 +++ test-data/unit/fixtures/list_hashable.pyi | 43 +++++++++ 7 files changed, 269 insertions(+), 29 deletions(-) create mode 100644 test-data/unit/fixtures/list_hashable.pyi diff --git a/mypy/checker.py b/mypy/checker.py index 3f2a8476ed934..2cd4b52ed78b3 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,48 @@ 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) + ) + if is_any_base: + if 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..76b6a697a6d9b 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[MemberExpr] = [] def add_type_vars(self) -> None: self.has_type_var_tuple_type = False @@ -5029,9 +5034,9 @@ def serialize(self, prefix: str, name: str) -> JsonDict: and fullname != prefix + "." + name and not (isinstance(self.node, Var) and self.node.from_module_getattr) ): - assert not isinstance( - self.node, PlaceholderNode - ), f"Definition of {fullname} is unexpectedly incomplete" + assert not isinstance(self.node, PlaceholderNode), ( + f"Definition of {fullname} is unexpectedly incomplete" + ) data["cross_ref"] = fullname return data data["node"] = self.node.serialize() @@ -5082,9 +5087,9 @@ def write(self, data: WriteBuffer, prefix: str, name: str) -> None: and fullname != prefix + "." + name and not (isinstance(self.node, Var) and self.node.from_module_getattr) ): - assert not isinstance( - self.node, PlaceholderNode - ), f"Definition of {fullname} is unexpectedly incomplete" + assert not isinstance(self.node, PlaceholderNode), ( + f"Definition of {fullname} is unexpectedly incomplete" + ) cross_ref = fullname write_str_opt(data, cross_ref) diff --git a/mypy/semanal.py b/mypy/semanal.py index c079a865af1de..0e25d2b87e2dc 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -775,9 +775,9 @@ def add_implicit_module_attrs(self, file_node: MypyFile) -> None: "builtins.dict", [str_type, AnyType(TypeOfAny.special_form)] ) if inst is None: - assert ( - not self.final_iteration - ), "Cannot find builtins.dict to add __annotations__" + assert not self.final_iteration, ( + "Cannot find builtins.dict to add __annotations__" + ) self.defer() return typ = inst @@ -1881,9 +1881,9 @@ def push_type_args( if self.get_defined_type_param(p.name): self.fail(f'"{p.name}" already defined as a type parameter', context) else: - assert self.add_symbol( - p.name, tv, context, no_progress=True, type_param=True - ), "Type parameter should not be discarded" + assert self.add_symbol(p.name, tv, context, no_progress=True, type_param=True), ( + "Type parameter should not be discarded" + ) return tvs @@ -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 # type: ignore[misc] 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,31 @@ 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" + ) + or ( + isinstance(member_type, TypeType) + and isinstance(member_type.item, AnyType) + ) + ): + # 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 +2699,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 +2747,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: @@ -7605,9 +7674,9 @@ def current_symbol_table( names = self.globals else: names_candidate = self.locals[-1 - i] - assert ( - names_candidate is not None - ), "Escaping comprehension from invalid scope" + assert names_candidate is not None, ( + "Escaping comprehension from invalid scope" + ) names = names_candidate break 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 From b8f0df25cb1fa185dc159c2788c8020ca2409ad7 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:55:26 +0000 Subject: [PATCH 2/5] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- mypy/nodes.py | 12 ++++++------ mypy/semanal.py | 18 +++++++++--------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/mypy/nodes.py b/mypy/nodes.py index 76b6a697a6d9b..75198385ba892 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -5034,9 +5034,9 @@ def serialize(self, prefix: str, name: str) -> JsonDict: and fullname != prefix + "." + name and not (isinstance(self.node, Var) and self.node.from_module_getattr) ): - assert not isinstance(self.node, PlaceholderNode), ( - f"Definition of {fullname} is unexpectedly incomplete" - ) + assert not isinstance( + self.node, PlaceholderNode + ), f"Definition of {fullname} is unexpectedly incomplete" data["cross_ref"] = fullname return data data["node"] = self.node.serialize() @@ -5087,9 +5087,9 @@ def write(self, data: WriteBuffer, prefix: str, name: str) -> None: and fullname != prefix + "." + name and not (isinstance(self.node, Var) and self.node.from_module_getattr) ): - assert not isinstance(self.node, PlaceholderNode), ( - f"Definition of {fullname} is unexpectedly incomplete" - ) + assert not isinstance( + self.node, PlaceholderNode + ), f"Definition of {fullname} is unexpectedly incomplete" cross_ref = fullname write_str_opt(data, cross_ref) diff --git a/mypy/semanal.py b/mypy/semanal.py index 0e25d2b87e2dc..971304a26c7b3 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -775,9 +775,9 @@ def add_implicit_module_attrs(self, file_node: MypyFile) -> None: "builtins.dict", [str_type, AnyType(TypeOfAny.special_form)] ) if inst is None: - assert not self.final_iteration, ( - "Cannot find builtins.dict to add __annotations__" - ) + assert ( + not self.final_iteration + ), "Cannot find builtins.dict to add __annotations__" self.defer() return typ = inst @@ -1881,9 +1881,9 @@ def push_type_args( if self.get_defined_type_param(p.name): self.fail(f'"{p.name}" already defined as a type parameter', context) else: - assert self.add_symbol(p.name, tv, context, no_progress=True, type_param=True), ( - "Type parameter should not be discarded" - ) + assert self.add_symbol( + p.name, tv, context, no_progress=True, type_param=True + ), "Type parameter should not be discarded" return tvs @@ -7674,9 +7674,9 @@ def current_symbol_table( names = self.globals else: names_candidate = self.locals[-1 - i] - assert names_candidate is not None, ( - "Escaping comprehension from invalid scope" - ) + assert ( + names_candidate is not None + ), "Escaping comprehension from invalid scope" names = names_candidate break else: From 1bd26bda3bef18deb1af894541148602383aa851 Mon Sep 17 00:00:00 2001 From: Sudhakar Date: Wed, 4 Nov 2026 10:36:45 +0530 Subject: [PATCH 3/5] fix(mypy): correct type annotation for deferred_member_bases --- mypy/nodes.py | 2 +- mypy/semanal.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mypy/nodes.py b/mypy/nodes.py index 75198385ba892..1e7251a01e923 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -3931,7 +3931,7 @@ def __init__(self, names: SymbolTable, defn: ClassDef, module_name: str) -> 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[MemberExpr] = [] + 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 971304a26c7b3..0751f70bed3cb 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, deferred_member_bases = bases_result # type: ignore[misc] + 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. From 0ca2ae310efaa3d32407c705d154ba15bd0e539c Mon Sep 17 00:00:00 2001 From: Sudhakar Date: Wed, 4 Nov 2026 13:08:43 +0530 Subject: [PATCH 4/5] refactor(mypy): accept any TypeType as a deferred member base; avoid regression for inferred class attrs --- mypy/checker.py | 5 +++-- mypy/semanal.py | 4 ---- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/mypy/checker.py b/mypy/checker.py index 2cd4b52ed78b3..aaea642d3cbaa 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -2855,8 +2855,9 @@ def check_deferred_member_bases(self, defn: ClassDef) -> None: or isinstance(typ, TypeType) and isinstance(typ.item, AnyType) ) - if is_any_base: - if self.options.disallow_subclassing_any: + 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 ) diff --git a/mypy/semanal.py b/mypy/semanal.py index 0751f70bed3cb..297c82cb9f17a 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -2667,10 +2667,6 @@ def analyze_base_classes( isinstance(member_type, Instance) and member_type.type.fullname == "builtins.type" ) - or ( - isinstance(member_type, TypeType) - and isinstance(member_type.item, AnyType) - ) ): # The attribute is a type object. Treat it like a variable # annotated with ``type``, which is accepted as a base class. From adc4e325dda768189679f5f334c518422c7b501d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 18:44:59 +0000 Subject: [PATCH 5/5] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- mypy/semanal.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index 297c82cb9f17a..a9621f42ac928 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -2661,12 +2661,9 @@ def analyze_base_classes( 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" - ) + 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.