Last active
May 4, 2023 20:33
-
-
Save Tishka17/29ead9f82c2c78cddf96a616c1dff0ae to your computer and use it in GitHub Desktop.
Managed widgets demo for aiogram-dialog
This file contains 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 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