This blog is now hosted at consciou.us

Monday, March 24, 2008

Singletons in Python

Since the project that I'm working on has a whole lot of nasty, boil the oceans, SQL queries, I thought it'd be best to cache information. Caching is great, but what I really need is an application-wide cache (not tied to a specific instance object).

Normally I use Singletons (from _Design Patterns_) to provide this functionality. Here's how to implement them in Python:

from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 (in the comments):

class Singleton(object):
def __new__(cls, *p, **k):
if not '_the_instance' in cls.__dict__:
cls._the_instance = object.__new__(cls)
return cls._the_instance

all you have to do then is inherit from Singleton, and it just works. This is actually cleaner than some other languages I've implemented Singletons in.

The real bonus, however, is the actual article that the posting above was about:

class Borg(object):
_state = {}
def __new__(cls, *p, **k):
self = object.__new__(cls, *p, **k)
self.__dict__ = cls._state
return self

That will share the state of the object across instances. No thinking about it.

No comments: