Pyright: Protocols, inheritance and method order

Created on 22 Oct 2020  路  2Comments  路  Source: microsoft/pyright

Describe the bug
Method definition order affects protocol implementation check.

To Reproduce
This code

from typing import Protocol


class ProtocolBase(Protocol):
    def a(self):
        ...

    def b(self):
        ...


class ProtocolExtended(ProtocolBase, Protocol):
    def c(self):
        ...


class Base:
    def a(self):
        pass


class ImplementsBase(Base):
    def b(self):
        pass


class ImplementsExtended(ImplementsBase):
    def c(self):
        pass


a: ProtocolExtended
a = ImplementsExtended()

checked using pyright gives the following error

  33:5 - error: Expression of type "ImplementsExtended" cannot be assigned to declared type "ProtocolExtended"
  聽聽"c" is an incompatible type
  聽聽"a" is an incompatible type
  聽聽"b" is an incompatible type
  聽聽聽聽Type "(self: ImplementsExtended) -> None" cannot be assigned to type "(self: ProtocolExtended) -> None"
  聽聽聽聽聽聽Parameter 2: type "ProtocolExtended" cannot be assigned to type "ImplementsExtended"
  聽聽聽聽聽聽聽聽"ProtocolExtended" is incompatible with "ImplementsExtended"
  聽聽聽聽Type "(self: Base) -> None" cannot be assigned to type "(self: ProtocolBase) -> None"
  聽聽聽聽聽聽Parameter 2: type "ProtocolBase" cannot be assigned to type "Base"
    ... (reportGeneralTypeIssues)

When I change ProtocolBase definition to

class ProtocolBase(Protocol):
    def b(self):
        ...

    def a(self):
        ...

than pyright does not produce any errors.

Expected behavior
I expect no errors to be reported in the first case.

VS Code extension or command-line
[email protected] , command-line

addressed in next version bug

All 2 comments

Thanks for the bug report and the great repro steps. This will be fixed in the next version. I've added your sample to our unit tests so this doesn't regress in the future.

The problem was due to a bad interaction between the protocol matching logic and the type inferred for the "self" parameter.

This is addressed in 1.1.82, which I just published. This will also be included in the next release of pylance.

Was this page helpful?
0 / 5 - 0 ratings