Skip to content

Instantly share code, notes, and snippets.

@luminousmen
Created October 29, 2019 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luminousmen/8981e8171ff9f57d0f7d208b67710110 to your computer and use it in GitHub Desktop.
Save luminousmen/8981e8171ff9f57d0f7d208b67710110 to your computer and use it in GitHub Desktop.
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
Copy link

It's a bit complicated snippet. I would use python module as a singleton.

@luminousmen
Copy link
Author

luminousmen commented Oct 29, 2019

@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