There is a base class C1, a subclass C2(C1) and a protocol P1 which C2 should be compatible with. All implementations of P1 are subclasses of C1, but we can’t make C1 a base class of a protocol. Then we have a function f1 that accepts an object of type C1 as argument a1. Another function f2 has a variable v1 of type P1 (e.g. a C2, but we want to keep it generic here for possible other subclasses of C1 that implement P1) and calls function f1 with a1=v1. Mypy would fail here because v1 is not C1. How can you annotate v1 so it conforms to C1 so it can be passed to f1 as a1 without modifying f1? We can modify P1 and everything about f2 and v1.

Snippet:

import typing


class C1:
  pass


class C2(C1):
  attr_1: int


class P1(typing.Protocol):
  attr_1: int


def f1(a1: C1) -> None:
  return


def f2(v1: P1) -> None:
  # v1 is always a subclass of C1
  f1(a1=v1)


f2(C2())  # C2 extends/implements both C1 and P1
0

There are 0 best solutions below