Skip to content

Instantly share code, notes, and snippets.

@arkanister
Last active December 6, 2018 14:29
Show Gist options
  • Select an option

  • Save arkanister/87e27cbc0e2e62e088d4f38040784d9e to your computer and use it in GitHub Desktop.

Select an option

Save arkanister/87e27cbc0e2e62e088d4f38040784d9e to your computer and use it in GitHub Desktop.
A simple implementation from singleton pattern using python classes.
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