Skip to content

Instantly share code, notes, and snippets.

@Willy-JL
Created July 17, 2021 16:12
Show Gist options
  • Save Willy-JL/b964ebe67276606c68b90e2d9fa995fd to your computer and use it in GitHub Desktop.
Save Willy-JL/b964ebe67276606c68b90e2d9fa995fd to your computer and use it in GitHub Desktop.
Event-Callback system using decorators
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