Skip to content

Instantly share code, notes, and snippets.

@gatspy
Last active May 4, 2016 08:36
Show Gist options
  • Save gatspy/f8644f39e97641aaa5f45fc22de9cf1b to your computer and use it in GitHub Desktop.
Save gatspy/f8644f39e97641aaa5f45fc22de9cf1b to your computer and use it in GitHub Desktop.
python -- singleton
# Method 1: A decorator
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class MySingleton(object):
pass
my1 = MySingleton()
my2 = MySingleton()
print id(my1) == id(my2)
print '----------------------'
# Method 2: metaclass
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(
Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
# Python2
class MyClass(object):
__metaclass__ = Singleton
m1 = MyClass()
m2 = MyClass()
print id(m1) == id(m2)
print '----------------------'
def singleton(class_):
class class_w(class_):
_instance = None
def __new__(class_, *args, **kwargs):
if class_w._instance is None:
class_w._instance = super(class_w,
class_).__new__(class_,
*args,
**kwargs)
class_w._instance._sealed = False
return class_w._instance
def __init__(self, *args, **kwargs):
if self._sealed:
return
super(class_w, self).__init__(*args, **kwargs)
self._sealed = True
class_w.__name__ = class_.__name__
return class_w
@singleton
class MyClass(object):
pass
print MyClass
print '---------------------'
import threading
class Singleton(object):
objs = {}
objs_locker = threading.Lock()
def __new__(cls, *args, **kwargs):
if cls in cls.objs:
return cls.objs[cls]
cls.objs_locker.acquire()
try:
if cls in cls.objs:
return cls.objs[cls]
cls.objs[cls] = super(Singleton, cls).__new__(cls)
finally:
cls.objs_locker.release()
return cls.objs[cls]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment