[Python] How do I make mypy treat my class as not being a subtype of object?

Discussão em 'Python' iniciado por Stack, Julho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write a class in Python where comparisons like MyClass(5) == 5 are considered type errors by mypy, even though in Python all user-defined classes inherit from object.

    My goal is to:

    1. Restrict comparisons to only instances of MyClass, so that MyClass(5) == 5 triggers a type checker error.
    2. Prevent passing MyClass instances into functions that expect generic object parameters, like this:

    from typing import Self

    class MyClass:
    def __init__(self: Self, x: int):
    self.x = x

    def __eq__(self: Self, other: "MyClass") -> bool:
    return self.x == other.x

    print(MyClass(5) == 5) # ❌ I want mypy to give an error here

    def abstract_comparator(a: object, b: object) -> bool:
    return a == b

    print(abstract_comparator(MyClass(5), 5)) # ❌ I also want an error here


    I tried:

    • Adding @overload definitions for __eq__, but mypy still treats MyClass as an object, so abstract_comparator(MyClass(5), 5) is accepted.
    • Creating fake protocols or dummy fields, but that either leaks into bar() or allows other unintended side effects.

    Ideally, I’d like a way to say “MyClass is not assignable to object” for the purposes of type checking, or a plugin / strict mode in mypy (or another tool like Pyright) that enforces __eq__ type contracts more strictly and disallows structural compatibility with object.

    Is there any way to express this intent to mypy or another type checker?

    Continue reading...

Compartilhe esta Página