Skip to content

Don't emit Liskov violations w.r.t. grandparent class if the violation cannot be fixed without breaking Liskov w.r.t. the parent class #2000

@t-moe

Description

@t-moe

Question

I have the following code:

from typing import Iterable
from collections import UserList

class Errors(UserList[str]):
    def __init__(self, initlist=None):
        super().__init__(initlist)

    def append(self, item: str) -> None:
        super().append(item)

    def extend(self, other: Iterable[str]) -> None:
        for item in other:
            self.append(item)

This fails with an error similar to

 uv run ty check
error[invalid-method-override]: Invalid override of method `append`
    --> error.py:8:9
     |
   6 |         super().__init__(initlist)
   7 |
   8 |     def append(self, item: str) -> None:
     |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Definition is incompatible with `MutableSequence.append`
   9 |         super().append(item)
     |
    ::: stdlib/typing.pyi:1112:9
     |
1110 |     def __delitem__(self, index: slice) -> None: ...
1111 |     # Mixin methods
1112 |     def append(self, value: _T) -> None:
     |         ------------------------------- `MutableSequence.append` defined here
1113 |         """S.append(value) -- append value to the end of the sequence"""
     |
info: This violates the Liskov Substitution Principle
info: rule `invalid-method-override` is enabled by default

error[invalid-method-override]: Invalid override of method `extend`
    --> error.py:11:9
     |
   9 |         super().append(item)
  10 |
  11 |     def extend(self, other: Iterable[str]) -> None:
     |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Definition is incompatible with `MutableSequence.extend`
  12 |         for item in other:
  13 |             self.append(item)
     |
    ::: stdlib/typing.pyi:1118:9
     |
1116 |         """S.clear() -> None -- remove all items from S"""
1117 |
1118 |     def extend(self, values: Iterable[_T]) -> None:
     |         ------------------------------------------ `MutableSequence.extend` defined here
1119 |         """S.extend(iterable) -- extend sequence by appending elements from the iterable"""
     |
info: This violates the Liskov Substitution Principle
info: rule `invalid-method-override` is enabled by default
Found 2 diagnostics

What am I missing?
Forgive me, if there is an obvious error hidden in plain sight. I havent written a lot of python lately..

Version

ty 0.0.2

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions