Skip to content

Commit 88e8f03

Browse files
authored
Add a section for incompatible overrides (python#8377)
This is according to changes suggested in python#7994
1 parent 8b3b1d8 commit 88e8f03

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

docs/source/common_issues.rst

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -750,4 +750,39 @@ Mypy has both type aliases and variables with types like ``Type[...]`` and it is
750750
tp = B # This is OK
751751
752752
def fun1(x: Alias) -> None: ... # This is OK
753-
def fun2(x: tp) -> None: ... # error: Variable "__main__.tp" is not valid as a type
753+
def fun2(x: tp) -> None: ... # error: Variable "__main__.tp" is not valid as a type
754+
755+
Incompatible overrides
756+
------------------------------
757+
758+
It's unsafe to override a method with a more specific argument type, as it violates
759+
the `Liskov substitution principle <https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle>`_. For return types, it's unsafe to override a method with a more general return type.
760+
761+
Here is an example to demonstrate this
762+
763+
.. code-block:: python
764+
765+
from typing import Sequence, List, Iterable
766+
767+
class A:
768+
def test(self, t: Sequence[int]) -> Sequence[str]:
769+
pass
770+
771+
# Specific argument type doesn't work
772+
class OverwriteArgumentSpecific(A):
773+
def test(self, t: List[int]) -> Sequence[str]:
774+
pass
775+
776+
# Specific return type works
777+
class OverwriteReturnSpecific(A):
778+
def test(self, t: Sequence[int]) -> List[str]:
779+
pass
780+
781+
# Generic return type doesn't work
782+
class OverwriteReturnGeneric(A):
783+
def test(self, t: Sequence[int]) -> Iterable[str]:
784+
pass
785+
786+
mypy won't report an error for ``OverwriteReturnSpecific`` but it does for ``OverwriteReturnGeneric`` and ``OverwriteArgumentSpecific``.
787+
788+
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.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy