python 2.1 singleton

Alex Martelli aleax at aleax.it
Wed Oct 15 06:19:50 EDT 2003


Duncan Booth wrote:

> "Alexiev Nikolay" <alexiev at activesolutions.bg> wrote in
> news:mailman.112.1066205794.2192.python-list at python.org:
> 
>> I need a simple implementation of singleton that will work on python
>> 2.1. I havn't got idea how to creat without staticmethod. Can you give
>> me a solution ??? 10x in advance
>> 
> 
> The simplest singleton implementation, which works for any version of
> Python is simply to use a module as your singleton instead of a class. You
> can get hold of the singleton object from anywhere simply by importing it.
> All functions defined in a module are effectively static methods on the
> module object.

Amen, Hallelujah.  This will be optimal any time you don't need some of the
capabilities that classes have over modules -- basically, inheritance and
special methods.  When you DO need to expose a class, I still suggest the
Borg nonpattern, http://www.aleax.it/5ep.html -- even though Guido hates
it with a vengeance, I'm still convinced it's superior to Singleton.

If you _do_ perversely want the Singleton DP no matter what, you don't
need static methods -- you can use a toplevel function just as well.

If you _do_ perversely want static methods in 2.1 no matter what,

class staticmethod:
    def __init__(self, thefunc): self.f = thefunc
    def __call__(self, *a, **k): return self.f(*a, **k)

and just use this staticmethod instead of 2.2's builtin one.


Alex





More information about the Python-list mailing list