Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created June 13, 2024 13:42
Show Gist options
  • Save mypy-play/d139ee55a5729d2ec5b63d4ceaeb5a33 to your computer and use it in GitHub Desktop.
Save mypy-play/d139ee55a5729d2ec5b63d4ceaeb5a33 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
from typing import Protocol, TypeVar
class Type1:
data1 = 1
def method1(self) -> None:
print(self.data1)
class Type2:
data2 = 2
def method2(self) -> None:
print(self.data2)
PossibleBaseClass = type[Type1 | Type2]
BaseClassT = TypeVar("BaseClassT", bound=PossibleBaseClass)
class ExampleT(Protocol[BaseClassT]):
base_class: type[BaseClassT]
class Example(ExampleT[BaseClassT]):
def __new__(
cls,
base_class: type[BaseClassT],
) -> BaseClassT:
new_class = type(
cls.__name__,
(cls, *base_class.__mro__),
{**cls.__dict__, **base_class.__dict__},
)
result = super(base_class, new_class).__new__(new_class)
result.base_class = base_class
return result
def method(self) -> None:
if self.base_class is Type1:
return self.method1()
if self.base_class is Type2:
return self.method2()
raise NotImplementedError
class ExampleSubclass(Example):
def upper_level_logic(self) -> None:
print("header")
self.method()
ExampleSubclass(base_class=Type1).upper_level_logic()
ExampleSubclass(base_class=Type2).upper_level_logic()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment