Created
July 17, 2021 16:12
-
-
Save Willy-JL/b964ebe67276606c68b90e2d9fa995fd to your computer and use it in GitHub Desktop.
Event-Callback system using decorators
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 collections import defaultdict | |
import functools | |
events_callbacks = defaultdict(list) | |
def callback(event_id: str): | |
def decorator_callback(func): | |
functools.wraps(func) | |
events_callbacks[event_id].append(func) | |
return func | |
return decorator_callback | |
def run_callbacks(event_id: str, *args): | |
for func in events_callbacks[event_id]: | |
func(*args) | |
# Example usage (in another file): | |
from events import callback | |
from events import run_callbacks | |
@callback("user_joined") | |
def greet_user(name, email): | |
send_email(email, f"Welcome, {name}!") | |
@callback("user_joined") | |
def db_add_user(name, email): | |
add_database_entry(name, email) | |
def user_signup() | |
name = input("Please insert your name: ") | |
email = input("Please inser your email address: ") | |
run_callbacks("user_joined", name, email) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment