You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/source/common_issues.rst
+36-1Lines changed: 36 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -750,4 +750,39 @@ Mypy has both type aliases and variables with types like ``Type[...]`` and it is
750
750
tp = B # This is OK
751
751
752
752
deffun1(x: Alias) -> None: ...# This is OK
753
-
deffun2(x: tp) -> None: ...# error: Variable "__main__.tp" is not valid as a type
753
+
deffun2(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
+
classA:
768
+
deftest(self, t: Sequence[int]) -> Sequence[str]:
769
+
pass
770
+
771
+
# Specific argument type doesn't work
772
+
classOverwriteArgumentSpecific(A):
773
+
deftest(self, t: List[int]) -> Sequence[str]:
774
+
pass
775
+
776
+
# Specific return type works
777
+
classOverwriteReturnSpecific(A):
778
+
deftest(self, t: Sequence[int]) -> List[str]:
779
+
pass
780
+
781
+
# Generic return type doesn't work
782
+
classOverwriteReturnGeneric(A):
783
+
deftest(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