Skip to content

Instantly share code, notes, and snippets.

@mahdiPourkazemi
Created April 16, 2024 15:22
Show Gist options
  • Save mahdiPourkazemi/7ef94606dc53bcb142a0ae221392e4f2 to your computer and use it in GitHub Desktop.
Save mahdiPourkazemi/7ef94606dc53bcb142a0ae221392e4f2 to your computer and use it in GitHub Desktop.
Register a function as plug-in, using decoration
import random
PLUGINS = dict()
def register(func):
"""Register a function as plug-in"""
#add function name and function to dictionary
PLUGINS[func.__name__] = func
return func
#example to put in dictionary
@register
def say_hello(name):
return f"hello {name}"
#example to put in dictionary
@register
def be_awesome(name):
return f"yo {name} , together we are the awesomest"
#example to run decoration plug-in desing pattern
def randomly_greet(name):
greeter,greeter_func= random.choice(list(PLUGINS.items()))
print(f"Using {greeter!r}")
return greeter_func
randomly_greet("Alice")
#uncomment line below and see the change
#randomly_greet("Alice")("mahdi")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment