Skip to content

Instantly share code, notes, and snippets.

@Gaasmann
Created May 22, 2022 16:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Gaasmann/beeebf526c163280cff796b842ee800a to your computer and use it in GitHub Desktop.
Save Gaasmann/beeebf526c163280cff796b842ee800a to your computer and use it in GitHub Desktop.
generic on variables
from abc import ABCMeta, abstractmethod
from typing import TypeVar, Generic, Type
class Item(metaclass=ABCMeta):
"""Base class for Item"""
class PaintedItem(Item):
"""a painted item."""
def __init__(self, color: str):
self._color = color
@property
def color(self) -> str:
return self._color
class TransparentItem(Item):
"""a transparent item"""
def __init__(self, transparency_ratio: float):
self._transparency_ratio = transparency_ratio
@property
def transparency_ratio(self) -> float:
return self._transparency_ratio
T = TypeVar("T", bound=Item)
class Check(Generic[T], metaclass=ABCMeta):
"""Checks on items"""
def __init__(self, item: T):
self._item = item
@abstractmethod
def check(self) -> bool:
"""True if all good"""
class CheckPaintColor(Check[PaintedItem]):
"""Checks for painted items."""
def check(self) -> bool:
return self._item.color == "blue"
class CheckTransparencyLevel(Check[TransparentItem]):
"""Check the transparent item isn't completely opaque."""
def check(self) -> bool:
return bool(self._item.transparency_ratio)
U = TypeVar("U", bound=Item)
# types on the list must be compatible with the type on the key
_CHECKS_TO_APPLY: dict[Type[U], list[Type[Check[U]]]] = {
CheckPaintColor: [CheckPaintColor],
TransparentItem: [CheckTransparencyLevel, CheckPaintColor], # CheckPaintColor is not valid here
}
def apply_checks(item: Item) -> bool:
return all(
check(item).check() for check in _CHECKS_TO_APPLY.get(item.__class__, [])
)
if __name__ == "__main__":
my_transparent_item = TransparentItem(0.8)
print("all good" if apply_checks(my_transparent_item) else "not good")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment