Singleton: my use-case for class decorators
It seems that class decorators will finally be making an appearance in Python 3 and Python 2.6. I've thought about using them from time to time, but the use-cases weren't that common. However, I did find myself writing a lot of singletons.
This time I wanted to write a bunch of boiler-plate objects, that should all be singletons. So I thought of class decorators, to avoid repetition. Here is my singleton implementation, and it seems to work under Python2.6:
>>> def eq_is(self, other):
... return self is other
...
>>> def singleton(cls):
... cls.__eq__ = eq_is
... return cls()
...
>>> @singleton
... class a(object):
... def __repr__(self):
... return 'foobar'
...
>>> a
foobar
>>> a == a
True
... return self is other
...
>>> def singleton(cls):
... cls.__eq__ = eq_is
... return cls()
...
>>> @singleton
... class a(object):
... def __repr__(self):
... return 'foobar'
...
>>> a
foobar
>>> a == a
True
I just can't wait for the new Pythons to come out of alpha!
Tags: class decorators, Programming, Python, Python 3000, Singleton
May 24th, 2008 at 3:13 pm
Python already has singletons built-in: they're called modules. For any job which requires precisely one instance of a thing, module semantics will get you precisely what you need.
June 1st, 2008 at 12:33 pm
I refer to singletons such as DefaultArg and Undefined which I wrote about. Python's built-in NotImplemented is also an example. Are you suggesting that these should be modules? Am I missing something here?