Skip to content

Instantly share code, notes, and snippets.

@apalala
Created May 22, 2012 16:17
Show Gist options
  • Save apalala/2770044 to your computer and use it in GitHub Desktop.
Save apalala/2770044 to your computer and use it in GitHub Desktop.
Singleton implementation in Python
def singleton(cls):
class Singleton(cls):
def __new__(cls, *args, **kwargs):
try:
return cls.__instance
except AttributeError:
cls.__instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
cls.instance = cls.__instance
return cls.__instance
t = Singleton
t.__name__ = cls.__name__
return t
if __name__ == '__main__':
@singleton
class First(object):
pass
@singleton
class Another(object):
pass
@singleton
class Third(list):
pass
s1 = First()
s2 = First()
assert s1 == s2
assert s1 == s2.instance
assert s2 == First.instance
a1 = Another()
a2 = Another()
assert a1 == a2
assert a1 == a2.instance
assert a2 == Another.instance
assert First.instance != Another.instance
t1 = Third()
assert len(t1) == 0
assert t1 == Third.instance
assert Third.instance != Another.instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment