Skip to content

Instantly share code, notes, and snippets.

@Tishka17
Last active May 4, 2023 20:33
Show Gist options
  • Save Tishka17/29ead9f82c2c78cddf96a616c1dff0ae to your computer and use it in GitHub Desktop.
Save Tishka17/29ead9f82c2c78cddf96a616c1dff0ae to your computer and use it in GitHub Desktop.
Managed widgets demo for aiogram-dialog
from typing import Protocol, TypeVar, Type, Dict, Any
ManagedW = TypeVar("ManagedW", covariant=True)
class Manageable(Protocol[ManagedW]):
def manage(self) -> ManagedW:
raise NotImplementedError
class ManagedRadio:
def print_radio(self) -> None:
print("manager radio")
class Radio(Manageable[ManagedRadio]):
def manage(self) -> ManagedRadio:
return ManagedRadio()
class Manager:
def __init__(self) -> None:
self.widgets: Dict[str, Any] = {}
def find(self, s: str, cls: Type[Manageable[ManagedW]]) -> ManagedW:
w = self.widgets[s]
if not isinstance(w, cls): # error in pycharm
raise ValueError
return w.manage()
m = Manager()
m.widgets["r"] = Radio()
r = m.find("r", Radio)
r.print_radio() # ok
# r.whatever() # error: "ManagedRadio" has no attribute "whatever"
#####
class ManagedButton:
def foo(self) -> None:
pass
class Button:
def manage(self) -> ManagedButton:
return ManagedButton()
class ManagedSubButton(ManagedButton):
def bar(self) -> None:
pass
class SubButton(Button):
def manage(self) -> ManagedSubButton:
return ManagedSubButton()
m.widgets["b"] = Button()
m.widgets["s"] = SubButton()
b = m.find("b", Button)
s = m.find("s", SubButton)
s.foo() # ok
s.bar() # ok
s.sss() # error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment