Last active
December 6, 2018 14:29
-
-
Save arkanister/87e27cbc0e2e62e088d4f38040784d9e to your computer and use it in GitHub Desktop.
A simple implementation from singleton pattern using python classes.
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
| def singleton(kls): | |
| """ | |
| A decorator to grant that only a single class | |
| instance will be created. | |
| Usage: | |
| >>> @singleton | |
| >>> class MyCustomClass: | |
| >>> ... do something ... | |
| >>> | |
| """ | |
| class MetaWrapper(type(kls)): | |
| def __init__(cls, name, bases, attrs): | |
| super().__init__(name, bases, attrs) | |
| cls._instance = None | |
| def __call__(cls, *args, **kwargs): | |
| if not cls._instance: | |
| # create a new instance based on the init arguments. | |
| cls._instance = super().__call__(*args, **kwargs) | |
| # returns the created instance | |
| return cls._instance | |
| class Wrapper(kls, metaclass=MetaWrapper): | |
| pass | |
| Wrapper.__name__ = kls.__name__ | |
| Wrapper.__repr__ = kls.__repr__ | |
| return Wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment