Singleton?

James T. Dennis jadestar at idiom.com
Sun Jan 27 20:32:38 EST 2002


On Sun, Jan 27, 2002 at 07:01:31PM -0600, Jason Orendorff 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/

 [Reading...] 

 That looks sort of like my first example.  In this case
 he creates a class Random, defines all of it's methods, et al,
 and then at then module load time he instantiates one instance
 and rebinds all of his function names (def for the class) as
 being references to the _inst (instantiated method).

 That seems to work because this is a module, and all modules
 are imported as singletons.  (Importing multiple times only 
 runs the import code once).





More information about the Python-list mailing list