python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.2k stars 2.78k forks source link

Return type "str" of "readline" incompatible with return type "bytes" in supertype "IOBase" [override] #9643

Open blueyed opened 3 years ago

blueyed commented 3 years ago

Since https://github.com/python/typeshed/pull/4145 (released with mypy 0.790) mypy fails with:

import io

class MyStringIO(io.StringIO):
    def readline(self, size=None) -> str:
        return super().readline(size)

Return type "str" of "readline" incompatible with return type "bytes" in supertype "IOBase" [override]

According to https://github.com/python/typeshed/pull/4145#issuecomment-639543492 this is likely a bug in mypy.

(mypy 0.800+dev.f220ce50725ed7f117832b9f03aed4d1a9508e00 (current master))

srittau commented 1 month ago

Currently, mypy only stops checking for LSP violations in the class hierarchy once it encounters a super class with a violation. Instead, it should stop after first encountering the method while walking up the inheritance tree, no matter whether that is a violation or not.

Here is an example not using typeshed:

class Base:
    def foo(self, x: int) -> None:
        pass

class Sub1(Base):
    def foo(self, x: str) -> None:  # type: ignore[override]
        pass

class Sub2(Sub1):
    def foo(self, x: str) -> None:  # Argument 1 of "foo" is incompatible with supertype "Base"; supertype defines the argument type as "int"  [override]
        pass

Sub2.foo should only be checked against Sub1.foo, not Base.foo as well.