what is it?
a class with only one instance
there are several singletons in python that you use frequently, including None, True, and False
singleton classes aren’t really used as often in python as in other languages. the effect of a singleton is usually better implemented as a global variable inside a module.
creating singleton decorator
import functools
# ...
def singleton(cls):
"""Make a class a Singleton class (only one instance)"""
@functools.wraps(cls)
def wrapper_singleton(*args, **kwargs):
if wrapper_singleton.instance is None:
wrapper_singleton.instance = cls(*args, **kwargs)
return wrapper_singleton.instance
wrapper_singleton.instance = None
return wrapper_singleton