Last active
December 17, 2018 21:23
-
-
Save jstncno/8dad50f6240484df9c7302b810a252d8 to your computer and use it in GitHub Desktop.
Python Singleton Instance
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 singletonmethod(func): | |
| def wrapped_classmethod(cls, *args, **kwargs): | |
| if cls._instance is None or type(cls._instance) != cls: | |
| cls._instance = cls() | |
| return func(cls._instance, *args, **kwargs) | |
| return wrapped_classmethod | |
| class Singleton(object): | |
| """ | |
| A Python Singleton instance. | |
| """ | |
| _instance = None | |
| def __init__(self): | |
| self.__shared_state = {} | |
| @classmethod | |
| def initialize(cls, *args, **kwargs): | |
| """Proxy constructor method, used to initialize the Singleton""" | |
| cls._instance = cls(*args, **kwargs) | |
| @classmethod | |
| @singletonmethod | |
| def get_state(self, key, default=None): | |
| return self.__shared_state.get(key, default) | |
| @classmethod | |
| @singletonmethod | |
| def set_state(self, key, val): | |
| self.__shared_state.update({key:val}) | |
| class FooSingleton(Singleton): | |
| def __init__(self, name='Foo'): | |
| super(FooSingleton, self).__init__() | |
| self.name = name | |
| @classmethod | |
| @singletonmethod | |
| def print_name(self): | |
| print self.name | |
| if __name__ == '__main__': | |
| FooSingleton.print_name() # prints 'Foo' | |
| FooSingleton.initialize('Bar') | |
| FooSingleton.print_name() # prints 'Bar' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment