Override not checked against base method's annotated `self`
Edited: the original repro, a plain
selfinImploverridingHasGet.get(self: HasValue), isn't a bug: the override accepts every receiver the base method accepts onImpl. It's replaced with an override whose declaredselfdoesn't accept them. See https://github.com/microsoft/pyright/issues/12012#issuecomment-7120150664.
Describe the bug
When a base method annotates self, pyright doesn't check an override's declared self against it. An override whose self accepts neither the child class nor the base method's self type gets no reportIncompatibleMethodOverride, though it rejects receivers the base method accepts.
Code or Screenshots
from typing import Protocol
class HasValue(Protocol):
value: int
class Base:
def get(self: "Base") -> int: ...
class Impl(Base):
def get(self: HasValue) -> int:
return self.value
0 errors, 0 warnings, 0 informations
VS Code extension or command-line
Command-line, pyright 1.1.414.
The original repro expected reportIncompatibleMethodOverride on this:
class HasGet(Protocol):
def get(self: HasValue) -> int: ...
class Impl(HasGet):
def get(self) -> int: ...
That override is compatible. By the Liskov substitution principle, an override's self must accept the intersection of the child class and the base method's declared self type, here Impl & HasValue: every Impl that is also a HasValue. A plain self accepts every Impl, so it accepts all of them. mypy_primer on #12015 showed typeshed and scipy-stubs relying on this pattern, and mypy, pyrefly and ty all accept it.
The gap that remains is an override whose declared self doesn't accept that intersection, as in the new repro: Impl.get(self: HasValue) rejects an Impl that isn't a HasValue, which Base.get accepts.