OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Provide a variable that implements both a protocol and a common base class so it works where the base class is expected [duplicate]

  • Thread starter Thread starter Yushin Washio
  • Start date Start date
Y

Yushin Washio

Guest
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:

Code:
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
<p>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.</p>
<p>Snippet:</p>
<pre class="lang-py prettyprint-override"><code>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
</code></pre>
 

Latest posts

D
Replies
0
Views
1
Dhanushka Amarakoon
D
S
Replies
0
Views
1
Shikhar Ambashta
S
Top