Skip to content

Instantly share code, notes, and snippets.

@darvil82
Last active December 17, 2022 15:13
Show Gist options
  • Save darvil82/4887c34329754f13197faac9bb0900da to your computer and use it in GitHub Desktop.
Save darvil82/4887c34329754f13197faac9bb0900da to your computer and use it in GitHub Desktop.
C# style event handler
from typing import Callable, Generic, TypeVar
T = TypeVar("T")
class EventHandler(Generic[T]):
callbacks: list [Callable[[T], None]] = []
def __iadd__(self, callback: Callable[[T], None]):
self.callbacks.append(callback)
return self
def __isub__(self, callback: Callable[[T], None]):
self.callbacks.remove(callback)
return self
def invoke(self, value: T):
for cb in self.callbacks:
cb(value)
def __call__(self, value: T):
self.invoke(value)
# -------------------------------- Testing -------------------------------------
def some_other_func(string: str):
print(f"nice! {string}")
def another_one(string: str):
print(f"eww: {string}")
def main():
s: EventHandler[str] = EventHandler()
# adding some callbacks
s += lambda v: print(v)
s += lambda v: print(f"I'm also being called! msg: {v}")
s += some_other_func
s += another_one
s -= another_one # eh, too mean, we'll just remove it
s.invoke("this is a message")
s("another one!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment