[Python-Dev] Re: Python-Dev Digest, Vol 8, Issue 91 (original) (raw)

Alex Martelli aleaxit at yahoo.com
Tue Mar 30 14:39:02 EST 2004


On 2004 Mar 30, at 17:09, Edward Loper wrote: ...

On a related note, now that Python has class methods, is there much point in a "singleton" pattern? In particular, why not just make a class that only defines class methods, and uses the class namespace to store variables (instead of an instance namespace)?

I think it's generally better to use a module when what you want is a module's functionality, and that's what you seem to be describing here. What using a class instance buys you is special methods (and possibly descriptors), e.g. sometimes you might want getattr (or a property) on "something of which there is a single instance" (avoiding the "singleton" word by paraphrase -- IMHO, "singleton" means "a set with a single element", NOT "the single element of that set", which is different -- anyway...). Generally, something like:

class foo(object): ''' whatever you want in here ''' foo = foo()

deals even with such obscure desiderata. Left out of all this (and a key force in the Gof4 writeup of "Singleton") is inheritance -- the ability for the user to subclass the singleton's class while still preserving the "there can be only one" constraint (best known as "the Highlander rule"...). IMHO, even if Guido hates it, my Borg non-pattern is still the best ("least bad") way to provide such VERY obscure feechurs. However, in the simpler approach above,

class _myspecialfoo(foo.class): ''' tweak a few things here ''' foo.class = _myspecialfoo

can also work. All which being said -- in almost 5 years of coding almost only in Python, I think I found myself needing anything "singletonish" (beyond a plain module), in production code, just once, and even that once went away once the code that used to rely on it got restructured, refactored and cleaned up. This personal experience is certainly a good part of what makes me believe that the importance of everything singletonish is vastly exaggerated in popular perception -- almost every other classic DP is more important and interesting, yet Singleton keeps coming up nevertheless...!

Alex



More information about the Python-Dev mailing list