Last active
July 25, 2020 04:49
-
-
Save walison17/1001a7d9be9051b4497e5091ca019989 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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