Singleton?

James T. Dennis jadestar at idiom.com
Mon Jan 28 23:14:16 EST 2002


Jason Orendorff <jason at jorendorff.com> wrote:

> James T. Dennis wrote:
>> Jason Orendorff wrote:
>>> There are many approaches.  My favorite, when it's feasible, is:

>>>   class _X:
>>>       """ NOTE: Do not instantiate this class!  Use x instead. """
>>>       pass

>>>   x = _X()  # singleton instance

>>  This is similar to an option I considered: [...]

> Perhaps it *looks* similar, but I assure you it's quite different
> in spirit.  The point of my approach above is:

>  - Anyone can write it.
>  - Anyone can read it.
>  - It uses no "tricks" or advanced language features.
>  - It's the quickest, simplest thing.

> My favorite Singleton in the Python standard library
> is class random.Random.  Consult the source (lines 633+)
> for all the clever details.

> (To find the source file, try
>     python -e "import random; print random.__file__"
>  but the source is in the .py file, not the .pyc file.)

> ## Jason Orendorff    http://www.jorendorff.com/

 Someone else pointed out that 2.2's __new__ staticmethod for classes
 can be used to create singletons.  __new__ is pretty close to the 
 __initialize__ that I was babbling about --- so I don't need to PEP it
 'cause it's already been done.

 Now, unto other patterns.  Anyone show me an example of a flyweight?




More information about the Python-list mailing list