Created
April 16, 2024 15:22
-
-
Save mahdiPourkazemi/7ef94606dc53bcb142a0ae221392e4f2 to your computer and use it in GitHub Desktop.
Register a function as plug-in, using decoration
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
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