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!

