Files
Carl Meyer cf41c5e876 [ty] Respect implicit __hash__ = None when a class defines __eq__ (#30145)
A class that defines `__eq__` and omits `__hash__` gets `__hash__ =
None` at class creation. ty previously found `object.__hash__` instead
and accepted instances of the class and its subclasses where `Hashable`
was required.

Account for the implicit `None` during class-member lookup. Subclasses
inherit it and can restore hashing by defining `__hash__`. Explicit and
generated hashes take precedence, including hashes supplied by frozen
dataclasses and Pydantic models. An equality protocol's own implicit
`None` also stays separate from the hash requirements it imposes on
structural implementations.

Fixes https://github.com/astral-sh/ty/issues/4941.

## Test plan

Compared ty with CPython on the issue reproducer. Python raised
`TypeError` for the equality-only class and its subclass, and accepted
the subclass that restored hashing. ty now rejects the same two
instances for a `Hashable` parameter.

Checked Pydantic 2.13.4 at runtime with frozen models that define
equality and with a base that provides a custom hash. Pydantic generated
hashes for the frozen models, preserved the inherited custom hash when
equality was inherited, and left `__hash__ = None` on the subclass that
redefined equality over the custom hash.

## Ecosystem report

The public run for
[`ac783ae`](https://github.com/astral-sh/ruff/commit/ac783ae505378aa9b46acd4e082f0edf6f5e678c)
found 23 stable diagnostic changes across five projects. We accept three
JAX false positives for this fix. ty loses the relationship between a
mask and the callable selected for its type. The other 20 changes follow
from recognizing equality-only classes as unhashable, including
corrected indexing overloads in static-frame and a missing hash
declaration in pandas-stubs. [Full ecosystem
report](https://github.com/astral-sh/ruff/pull/30145#issuecomment-6700457278)
2026-11-13 08:51:23 -08:00

15 KiB

Tests regarding abstract classes

Instantiation is forbidden

Classes with unimplemented abstract methods cannot be instantiated. Type checkers are expected to detect possible attempts to instantiate abstract classes:

import abc
from typing import Protocol

class AbstractBase(abc.ABC):
    @abc.abstractmethod
    def bar(self): ...

class StillAbstract(AbstractBase): ...

# snapshot: abstract-class-instantiation
StillAbstract()

class AbstractBase2(abc.ABC):
    @abc.abstractmethod
    def bar(self): ...
    @abc.abstractmethod
    def bar2(self): ...

# snapshot: abstract-class-instantiation
AbstractBase2()

class StillAbstract2(AbstractBase2): ...

# error: [abstract-class-instantiation]
StillAbstract2()

class AbstractBase3(Protocol):
    def bar(self) -> None: ...

class StillAbstract3(AbstractBase3): ...

# snapshot: abstract-class-instantiation
StillAbstract3()
error[abstract-class-instantiation]: Cannot instantiate abstract class `StillAbstract`
  --> src/mdtest_snippet.py:11:1
   |
11 |   StillAbstract()
   |   ^^^^^^^^^^^^^^^ `bar` is unimplemented
   |
  ::: src/mdtest_snippet.py:5:5
   |
 5 | /     @abc.abstractmethod
 6 | |     def bar(self): ...
   | |______________________- `bar` declared as abstract on superclass `AbstractBase`


error[abstract-class-instantiation]: Cannot instantiate abstract class `AbstractBase2`
  --> src/mdtest_snippet.py:20:1
   |
20 |   AbstractBase2()
   |   ^^^^^^^^^^^^^^^ Abstract methods `bar` and `bar2` are unimplemented
   |
  ::: src/mdtest_snippet.py:14:5
   |
14 | /     @abc.abstractmethod
15 | |     def bar(self): ...
   | |______________________- `bar` declared as abstract


error[abstract-class-instantiation]: Cannot instantiate abstract class `StillAbstract3`
  --> src/mdtest_snippet.py:33:1
   |
33 | StillAbstract3()
   | ^^^^^^^^^^^^^^^^ `bar` is unimplemented
   |
  ::: src/mdtest_snippet.py:28:5
   |
28 |     def bar(self) -> None: ...
   |     -------------------------- `bar` declared as abstract on superclass `AbstractBase3`
info: `AbstractBase3.bar` is implicitly abstract because `AbstractBase3` is a `Protocol` class and `bar` lacks an implementation
  --> src/mdtest_snippet.py:27:7
   |
27 | class AbstractBase3(Protocol):
   |       ----------------------- `AbstractBase3` declared here
help: Change the body of `bar` to `return` or `return None` if it was not intended to be abstract

Abstract methods can be concretely overridden by synthesized methods:

from abc import ABC, abstractmethod
from dataclasses import dataclass
from functools import total_ordering

class AbstractOrdered(ABC):
    @abstractmethod
    def __lt__(self, other): ...

@dataclass(order=True)
class ConcreteOrdered(AbstractOrdered): ...

ConcreteOrdered()  # ok

@total_ordering
class AlsoConcreteOrdered(AbstractOrdered):
    def __gt__(self, other): ...

# total_ordering does not override a comparison method
# if it already exists in the MRO, even if the one that
# exists in the MRO is abstract!
#
# error: [abstract-class-instantiation]
AlsoConcreteOrdered()

We also allow abstract methods or properties to be "overridden" by a ClassVar annotation, even if it is not accompanied by a binding in the class body: we assume that a class like this will have the override added dynamically (e.g., by a metaclass):

from typing import ClassVar, Callable

class AbstractDynamic(ABC):
    @property
    @abstractmethod
    def f(self) -> int: ...
    @abstractmethod
    def g(self) -> str: ...

class ConcreteDynamic(AbstractDynamic):
    f: ClassVar[int]
    g: ClassVar[Callable[..., str]]

ConcreteDynamic()  # ok

But if the annotation does not use ClassVar, we do not see that as overriding the abstract method:

class StillAbstractDynamic(AbstractDynamic):
    f: int
    g: Callable[..., str]

# snapshot: abstract-class-instantiation
StillAbstractDynamic()
error[abstract-class-instantiation]: Cannot instantiate abstract class `StillAbstractDynamic`
  --> src/mdtest_snippet.py:76:1
   |
76 | StillAbstractDynamic()
   | ^^^^^^^^^^^^^^^^^^^^^^ Abstract methods `f` and `g` are unimplemented
   |
  ::: src/mdtest_snippet.py:62:9
   |
62 |     def f(self) -> int: ...
   |         - `f` declared as abstract on superclass `AbstractDynamic`
info: The instance-attribute annotation for `f` does not override the abstract method
help: Either assign a value or add `ClassVar` to this declaration
  --> src/mdtest_snippet.py:72:5
   |
72 |     f: int
   |     - Instance-attribute declaration

Abstract methods can be overridden by mixin classes, but the concrete override on the mixin must come earlier in the MRO:

class AbstractMixin(ABC):
    @abstractmethod
    def bar(self): ...

class ConcreteMixin:
    def bar(self): ...

class Sub1(AbstractMixin, ConcreteMixin): ...
class Sub2(ConcreteMixin, AbstractMixin): ...

Sub1()  # error: [abstract-class-instantiation]
Sub2()  # ok

When a class has many unimplemented abstract methods, the diagnostic lists only a few unless --verbose is enabled.

from typing import Protocol

class Abstract(Protocol):
    def aaaaaaaaa(self) -> int: ...
    def bbbbbbbb(self) -> int: ...
    def cccccccc(self) -> int: ...
    def dddddddddd(self) -> int: ...
    def eeeeeeee(self) -> int: ...
    def fffffff(self) -> int: ...
    def ggggggggg(self) -> int: ...
    def hhhhhhhhh(self) -> int: ...
    def iiiiiiiiii(self) -> int: ...
    def kkkkkkkkk(self) -> int: ...

class StillSadlyAbstract(Abstract): ...

# snapshot: abstract-class-instantiation
StillSadlyAbstract()
error[abstract-class-instantiation]: Cannot instantiate abstract class `StillSadlyAbstract`
   --> src/mdtest_snippet.py:106:1
    |
106 | StillSadlyAbstract()
    | ^^^^^^^^^^^^^^^^^^^^ 10 abstract methods are unimplemented, including `aaaaaaaaa`, `bbbbbbbb` and `cccccccc`
    |
   ::: src/mdtest_snippet.py:92:5
    |
 92 |     def aaaaaaaaa(self) -> int: ...
    |     ------------------------------- `aaaaaaaaa` declared as abstract on superclass `Abstract`
info: Use `--verbose` to see all 10 unimplemented abstract methods
info: `Abstract.aaaaaaaaa` is implicitly abstract because `Abstract` is a `Protocol` class and `aaaaaaaaa` lacks an implementation
  --> src/mdtest_snippet.py:91:7
   |
91 | class Abstract(Protocol):
   |       ------------------ `Abstract` declared here

Verbose diagnostics

With --verbose, the diagnostic lists every unimplemented abstract method.

verbose = true
from typing import Protocol

class Abstract(Protocol):
    def first(self) -> int: ...
    def second(self) -> int: ...
    def third(self) -> int: ...
    def fourth(self) -> int: ...

class StillAbstract(Abstract): ...

# snapshot: abstract-class-instantiation
StillAbstract()
error[abstract-class-instantiation]: Cannot instantiate abstract class `StillAbstract`
  --> src/mdtest_snippet.py:12:1
   |
12 | StillAbstract()
   | ^^^^^^^^^^^^^^^ Abstract methods `first`, `second`, `third` and `fourth` are unimplemented
   |
  ::: src/mdtest_snippet.py:4:5
   |
 4 |     def first(self) -> int: ...
   |     --------------------------- `first` declared as abstract on superclass `Abstract`
info: `Abstract.first` is implicitly abstract because `Abstract` is a `Protocol` class and `first` lacks an implementation
 --> src/mdtest_snippet.py:3:7
  |
3 | class Abstract(Protocol):
  |       ------------------ `Abstract` declared here
info: rule `abstract-class-instantiation` is enabled by default

Abstract methods without ABCMeta

The abstractmethod decorator requires subclasses to implement a method even if the class does not use ABCMeta. A default implementation does not remove that requirement. Invalid constructor calls still retain their inferred instance type for error recovery.

from abc import abstractmethod

class Abstract:
    @abstractmethod
    def method(self) -> int:
        return 42

# error: [abstract-class-instantiation]
reveal_type(Abstract())  # revealed: Abstract

class Concrete(Abstract):
    def method(self) -> int:
        return super().method()

Concrete()  # ok

Generic abstract classes and aliases

Specializing or aliasing an abstract class does not implement its abstract methods. A concrete subclass can be instantiated with the same type arguments.

[environment]
python-version = "3.12"
from abc import ABC, abstractmethod

class Abstract[T](ABC):
    @abstractmethod
    def method(self) -> T: ...

Abstract[int]()  # error: [abstract-class-instantiation]
Alias = Abstract[str]
Alias()  # error: [abstract-class-instantiation]

class Concrete[T](Abstract[T]):
    def method(self) -> T:
        raise NotImplementedError

Concrete[int]()  # ok

Constructor calls through type[]

A type[Abstract] parameter can refer to a concrete subclass, so calling it is allowed. We also continue to accept abstract class objects as arguments; this check concerns direct construction, not assignability to type[].

from abc import ABC, abstractmethod

class Abstract(ABC):
    @abstractmethod
    def method(self) -> int: ...

class Concrete(Abstract):
    def method(self) -> int:
        return 42

def construct(cls: type[Abstract]) -> Abstract:
    return cls()  # ok

construct(Concrete)  # ok
construct(Abstract)  # ok

Abstract property accessors

A property remains abstract if its setter or deleter is abstract, even when its getter has a concrete implementation. Replacing the abstract accessor makes the subclass concrete.

from abc import ABC, abstractmethod

class AbstractSetter(ABC):
    @property
    def value(self) -> int:
        return 0

    @value.setter
    @abstractmethod
    def value(self, value: int) -> None: ...

AbstractSetter()  # error: [abstract-class-instantiation]

class ConcreteSetter(AbstractSetter):
    @AbstractSetter.value.setter
    def value(self, value: int) -> None: ...

ConcreteSetter()  # ok

class AbstractDeleter(ABC):
    @property
    def value(self) -> int:
        return 0

    @value.deleter
    @abstractmethod
    def value(self) -> None: ...

AbstractDeleter()  # error: [abstract-class-instantiation]

class ConcreteDeleter(AbstractDeleter):
    @AbstractDeleter.value.deleter
    def value(self) -> None: ...

ConcreteDeleter()  # ok

Implicit override of an abstract hash

Defining __eq__ implicitly sets __hash__ = None, which overrides the abstract method on collections.abc.Hashable.

from collections.abc import Hashable

class Concrete(Hashable):
    __eq__ = object.__eq__

Concrete()  # ok

Slots overriding abstract properties

A slot creates a descriptor in the class namespace, which overrides an inherited abstract property. The resulting concrete class can be marked final.

from abc import ABC, abstractmethod
from typing import final

class Abstract(ABC):
    @property
    @abstractmethod
    def value(self) -> int: ...
    @value.setter
    @abstractmethod
    def value(self, value: int) -> None: ...

# ok: the abstract property is implemented by the slot
@final
class Concrete(Abstract):
    __slots__ = ("value",)

Concrete()  # ok

Slots and abstract properties in the MRO

A slot inherited from a mixin overrides an abstract property when the mixin comes first in the MRO.

from abc import ABC, abstractmethod

class Abstract(ABC):
    @property
    @abstractmethod
    def value(self) -> int: ...

class SlotMixin:
    __slots__ = ("value",)

class Concrete(SlotMixin, Abstract): ...

Concrete()  # ok

With the bases reversed, the class remains abstract. The getter-only property also removes writes permitted by the mixin's slot, so the class definition receives an override error.

class StillAbstract(Abstract, SlotMixin): ...  # error: [incompatible-property-override]

StillAbstract()  # error: [abstract-class-instantiation]

Further subclasses do not change that ordering, even though they inherit the mixin's slot.

class StillAbstractChild(StillAbstract):
    __slots__ = ()

StillAbstractChild()  # error: [abstract-class-instantiation]

Dataclass slots overriding abstract properties

Slots generated by dataclass(slots=True) also override inherited abstract properties.

from abc import ABC, abstractmethod
from dataclasses import dataclass

class Abstract(ABC):
    @property
    @abstractmethod
    def value(self) -> int: ...

@dataclass(slots=True)
class Concrete(Abstract):
    value: int

Concrete(1)  # ok

Methods in stub files

Protocol methods in stub files are abstract only when explicitly decorated with abstractmethod. An empty body can also describe a concrete default implementation whose body is omitted from the stub.

interface.pyi:

from abc import abstractmethod
from typing import Protocol

class Interface(Protocol):
    def default(self) -> None: ...
    @abstractmethod
    def required(self) -> int: ...

main.py:

from interface import Interface

class StillAbstract(Interface): ...

StillAbstract()  # error: [abstract-class-instantiation] "unimplemented abstract method `required`"

class Concrete(Interface):
    def required(self) -> int:
        return 42

Concrete()  # ok

Abstract overloads

An abstract overload keeps a method abstract even when its implementation is not decorated with abstractmethod. The implementation can provide a body for subclasses to call with super().

from abc import ABC, abstractmethod
from typing import overload

class Abstract(ABC):
    @overload
    @abstractmethod
    def method(self, value: int) -> int: ...
    @overload
    @abstractmethod
    def method(self, value: str) -> str: ...
    def method(self, value: int | str) -> int | str:
        return value

Abstract()  # error: [abstract-class-instantiation]

Aliased abstract methods

Assigning an abstract method to another class preserves its abstractness, even when that class does not inherit from the class that defined the method.

from abc import abstractmethod

class Abstract:
    @abstractmethod
    def method(self) -> None: ...

class Alias:
    method = Abstract.method

Alias()  # error: [abstract-class-instantiation]

A decorator can also return an abstract method. Here the decorator replaces Decorated.method with Abstract.method, so Decorated is abstract.

from abc import ABC
from collections.abc import Callable
from typing import TypeVar

T = TypeVar("T")

def replace_with(value: T) -> Callable[[object], T]:
    return lambda _: value

class Decorated(ABC):
    @replace_with(Abstract.method)
    def method(self) -> None:
        pass

Decorated()  # error: [abstract-class-instantiation]

Python applies the inner decorator first. It returns a plain object, which the outer decorator replaces with Abstract.method.

class Stacked(ABC):
    @replace_with(Abstract.method)
    @replace_with(object())
    def method(self) -> None:
        pass

Stacked()  # error: [abstract-class-instantiation]