[Python-Dev] PEP 318: Singleton decorator

Phillip J. Eby pje at telecommunity.com
Tue Mar 30 09:58:06 EST 2004


At 05:17 AM 3/30/04 -0600, Ka-Ping Yee wrote:
>Hi folks.
>
>Earlier messages suggested a nice singleton decorator, which is shown
>in the draft PEP:
>
>     def singleton(cls):
>         return cls()
>
>     class MyClass [singleton]:
>         ...
>
>This has been mentioned as an argument against requiring or recommending
>that decorators accept and return callables.
>
>But i don't think this is a good way to write a singleton, because then
>the user of the class has to get instances by saying "MyClass" instead
>of "MyClass()".

That's a stylistic decision.  IMO, it's more pythonic to *not* call a 
constructor.  One does not, after all, call modules in order to "construct" 
them, and modules are a prime example of singletons in Python.

What benefit is there to forcing people to perform a call operation that 
doesn't *do* anything?


>I respectfully suggest that the PEP use the latter implementation in
>its singleton example instead.

I respectfully disagree.  :)




More information about the Python-Dev mailing list