Created
March 18, 2023 00:27
-
-
Save lmazuel/a305288d81d05559c8bd9585445ca33a to your computer and use it in GitHub Desktop.
Typing with generic and inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import TypeVar, Optional, Generic, Protocol | |
class Additive(Protocol): | |
def __add__(self: 'MyReturnType', other: 'MyReturnType') -> 'MyReturnType': ... | |
MyReturnType = TypeVar("MyReturnType", bound=Additive) | |
class Foo(Generic[MyReturnType]): | |
def __init__(self, input: MyReturnType) -> None: | |
self._input = input | |
def concat(self, value: MyReturnType) -> MyReturnType: | |
return self._input + value | |
f1 = Foo(2) | |
f1.concat(5) | |
f2 = Foo("ba") | |
f2.concat("glfkjh") | |
NewThing = TypeVar("NewThing", bound=Additive) | |
class Bar(Foo[NewThing], Generic[NewThing]): | |
def bla(self): | |
print(self._input) | |
f3 = Bar(2) | |
f3.concat(5) | |
f3.bla() | |
reveal_locals() | |
reveal_type(f3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment