Programming Python

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
>>> a == a

I just can’t wait for the new Pythons to come out of alpha!

2 replies on “Singleton: my use-case for class decorators”

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.

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?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.