Skip to content

Instantly share code, notes, and snippets.

@walison17
Last active July 25, 2020 04:49
Show Gist options
  • Save walison17/1001a7d9be9051b4497e5091ca019989 to your computer and use it in GitHub Desktop.
Save walison17/1001a7d9be9051b4497e5091ca019989 to your computer and use it in GitHub Desktop.
from collections import defaultdict
from typing import Callable
# Store all event listeners
LISTENERS_REGISTRY = defaultdict(list)
# events
PAYMENT_STATUS_CHANGED = 'payment_status_changed'
CONTACT_INFO = 'contact_info'
def call_listeners(event: str, **payload):
"""Call all listeners registered for an event"""
listeners = LISTENERS_REGISTRY.get(event)
for listener in listeners:
listener(**payload)
def remove_listeners(event: str):
"""Remove all listeners registered for an event"""
LISTENERS_REGISTRY[event].clear()
def register_listener(event: str) -> Callable:
"""Register a listener for an event"""
def decorator(func: Callable) -> Callable:
LISTENERS_REGISTRY[event].append(func)
return func
return decorator
add_payment_status_changed = register_listener(PAYMENT_STATUS_CHANGED)
add_contact_info_listener = register_listener(CONTACT_INFO)
# Better style for decorator usage
payment_status_changed = add_payment_status_changed
contact_info_listener = add_contact_info_listener
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment