Skip to content

Using type Self allows to violate Liskov Substitution Principle #15619

Open
@AntPeixe

Description

@AntPeixe

Bug Report

By using Self in the type of a method's argument it's possible to violate the Liskov Substitution Principle without any warning.

(A clear and concise description of what the bug is.)

To Reproduce

Mypy raises no issue on this code although SubClass.update is clearly violating LSP.

from typing_extensions import Self

class BaseClass:
    foo: int
    def update(self, other: Self) -> None:
        self.foo = other.foo

class SubClass(BaseClass):
    bar: int
    def update(self, other: Self) -> None:  # problem here
        super().update(other)
        self.bar = other.bar

Expected Behavior

I'd expect that using Self would raise the warning similarly to specifying the class. Mypy raises the issue on the below.

from typing_extensions import Self

class BaseClass:
    foo: int
    def update(self, other: BaseClass) -> None:
        self.foo = other.foo

class SubClass(BaseClass):
    bar: int
    def update(self, other: SubClass) -> None:  # problem here
        super().update(other)
        self.bar = other.bar

Your Environment

  • Mypy version used: 1.4.1
  • Python version used: 3.10.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-inheritanceInheritance and incompatible overridestopic-self-typesTypes for self

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions