• Skip to primary navigation
  • Skip to main content

Algorithm.co.il

  • About
  • Best Posts
  • Origami
  • Older Projects

Singleton: my use-case for class decorators

Posted on 2008-05-01 by lorg 2 Comments

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

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

Filed under: Programming, Python

Reader Interactions

Comments

  1. Paul says

    2008-05-24 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.

    Reply
  2. lorg says

    2008-06-01 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?

    Reply

Leave a Reply Cancel reply

© 2026 Algorithm.co.il - Algorithms, for the heck of it