Created
April 15, 2020 19:03
-
-
Save kaulketh/aacd538e054943803943b951183710c4 to your computer and use it in GitHub Desktop.
python singleton with metaclass
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): | |
""" A metaclass that creates a Singleton base class when called. | |
Works in Python 2 & 3 | |
https://www.it-swarm.dev/de/python/ein-singleton-python-erstellen/972393601 | |
""" | |
_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 Singleton(_Singleton('SingletonMeta', (object,), {})): | |
""" Works in Python 2 & 3 | |
https://www.it-swarm.dev/de/python/ein-singleton-python-erstellen/972393601 | |
""" | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment