Last active
June 4, 2022 21:57
-
-
Save kkroesch/7cba17629d77ab53fadfbc4ae9e9ee7d to your computer and use it in GitHub Desktop.
Plugin registry implementation
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
| class Singleton(type): | |
| _instances = {} | |
| def __call__(cls, *args, **kwargs): | |
| if cls not in cls._instances: | |
| cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) | |
| return cls._instances[cls] | |
| class Registry(metaclass=Singleton): | |
| """Management for plugins as a singleton. | |
| """ | |
| def __init__(self): | |
| self._plugins = dict() | |
| def register(self, func): | |
| self._plugins[func.__name__] = func | |
| return func | |
| def get_plugins(self): | |
| return self._plugins.items() | |
| def doc_plugins(self): | |
| return [(name, func.__doc__) for name, func in self._plugins.items()] | |
| def register(func): | |
| Registry().register(func) | |
| def plugins(): | |
| return Registry().get_plugins() |
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 | |
| from plugin import Registry, register | |
| @register | |
| def say_hello(name): | |
| """Standard hello function""" | |
| return f"Hello {name}" | |
| @register | |
| def be_awesome(name): | |
| """Alternative awesome hello function""" | |
| return f"Yo {name}, together we are the awesomest!" | |
| def randomly_greet(name): | |
| greeter, greeter_func = random.choice(list(Registry().get_plugins())) | |
| print(f"Using {greeter!r}") | |
| return greeter_func(name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment