Skip to content

Instantly share code, notes, and snippets.

@taozle
Last active November 20, 2015 07:54
Show Gist options
  • Save taozle/faf32d0d781eff0ebf7a to your computer and use it in GitHub Desktop.
Save taozle/faf32d0d781eff0ebf7a to your computer and use it in GitHub Desktop.
Singleton implementations
import functools
def singleton(cls, *args, **kwargs):
instances = {}
@functools.wraps(cls)
def wrapper():
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
class Singleton(type):
def __init__(self, name, bases, dct):
super(Singleton, self).__init__(name, bases, dct)
self.instance = None
def __call__(self, *args, **kw):
if self.instance is None:
self.instance = super(Singleton, self).__call__(*args, **kw)
return self.instance
class A(object):
__metaclass__ = Singleton
def __init__(self):
self.xx = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment