def singleton(cls):
instances = {}
def wrapper(*args,**kwargs):
if cls not in instances:
instances[cls] = cls(*args,**kwargs)
return instances[cls]
return wrapper
@singleton
class Foo(object):
pass
class Singleton(object):
def __new__(cls,*args,**kwargs):
if not hasattr(cls,"_instance"):
cls._instance = object.__new__(cls)
return cls._instance
class Foo2(Singleton):
pass
class Singleton(type):
def __call__(cls,*args,**kwargs):
if not hasattr(cls,"_instance"):
cls._instance = super(Singleton,cls).__call__(*args,**kwargs)
return cls._instance
class Foo2(metaclass=Singleton):
pass