Singleton pattern in Python
Filed under Python on jul 23, 2010
Just came up with a simple pattern for singletons in Python using a class decorator:
def singleton(cls):
instances = {}
def instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return instance
Little demo:
>>> @singleton ... class Foo(object): ... pass ... >>> f1 = Foo() >>> print id(f1) 3077430124 >>> f2 = Foo() >>> print ...
Older posts
-
href.be services ported to GAE
Posted 6 days, 17 hours ago
-
href.be tools
Posted 1 week ago
-
Python ternary operation
Posted 1 week ago
-
We're in this together
Posted 2 weeks, 2 days ago
-
Django chroot, securing your web application hosting
Posted 1 month, 3 weeks ago
-
Slicing an ext3 disk for Time Machine
Posted 2 months ago
-
inode usage count in Linux
Posted 2 months, 2 weeks ago
-
Pixels: 8 bit attack
Posted 3 months, 3 weeks ago
-
Python MIME Magic
Posted 3 months, 4 weeks ago