Using type Self allows to violate Liskov Substitution Principle
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the Python reproducer in the issue and compare the Self-based override with the explicit BaseClass and SubClass annotations. Trace mypy's override checking for method parameters involving Self, then add regression coverage for the reported case. Done means mypy reports the invalid override while preserving valid Self usage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100