Created
October 29, 2019 09:28
-
-
Save luminousmen/8981e8171ff9f57d0f7d208b67710110 to your computer and use it in GitHub Desktop.
This file contains 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
from weakref import WeakValueDictionary | |
class Singleton(type): | |
_instances = WeakValueDictionary() | |
def __call__(cls, *args, **kwargs): | |
if cls not in cls._instances: | |
instance = super(Singleton, cls).__call__(*args, **kwargs) | |
cls._instances[cls] = instance | |
return cls._instances[cls] | |
class Config(metaclass=Singleton): | |
pass |
@easysugar Agreed, python modules are pure singletons and they don't have much complexity but I think I like the explicit usage of this construction more(even if I'll use modules anyway:)):
cfg = Config()
or even using context managers:
with Config() as cfg:
pass
instead of
from config as cfg
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's a bit complicated snippet. I would use python module as a singleton.