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

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

This entry was posted in Programming, Python and tagged , , , , . Bookmark the permalink.

2 Responses to Singleton: my use-case for class decorators

  1. Paul says:

    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.

  2. lorg says:

    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?