Search

Recent

Tags

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 ...

… read more

Older posts

  1. href.be services ported to GAE

    Posted 6 days, 17 hours ago

  2. href.be tools

    Posted 1 week ago

  3. Python ternary operation

    Posted 1 week ago

  4. We're in this together

    Posted 2 weeks, 2 days ago

  5. Django chroot, securing your web application hosting

    Posted 1 month, 3 weeks ago

  6. Slicing an ext3 disk for Time Machine

    Posted 2 months ago

  7. inode usage count in Linux

    Posted 2 months, 2 weeks ago

  8. Pixels: 8 bit attack

    Posted 3 months, 3 weeks ago

  9. Python MIME Magic

    Posted 3 months, 4 weeks ago