Incompatible overrides

It’s unsafe to override a method with a more specific argument type, as it violatesthe Liskov substitution principle. For return types, it’s unsafe to override a method with a more general return type.

Here is an example to demonstrate this

  1. from typing import Sequence, List, Iterable
  2.  
  3. class A:
  4. def test(self, t: Sequence[int]) -> Sequence[str]:
  5. pass
  6.  
  7. # Specific argument type doesn't work
  8. class OverwriteArgumentSpecific(A):
  9. def test(self, t: List[int]) -> Sequence[str]:
  10. pass
  11.  
  12. # Specific return type works
  13. class OverwriteReturnSpecific(A):
  14. def test(self, t: Sequence[int]) -> List[str]:
  15. pass
  16.  
  17. # Generic return type doesn't work
  18. class OverwriteReturnGeneric(A):
  19. def test(self, t: Sequence[int]) -> Iterable[str]:
  20. pass

mypy won’t report an error for OverwriteReturnSpecific but it does for OverwriteReturnGeneric and OverwriteArgumentSpecific.

We can use # type: ignore[override] to silence the error (add it to the line that genreates the error) if type safety is not needed.