Singleton?
Jason Orendorff
jason at jorendorff.com
Sun Jan 27 20:01:31 EST 2002
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/
More information about the Python-list
mailing list