singleton in python ?

Steve Holden sholden at holdenweb.com
Fri May 10 09:56:46 EDT 2002


"Marcel L.K. Opsteegh" <mlk_opsteegh at yahoo.com> wrote in message
news:db9b83c9.0205100524.1c6a03d5 at posting.google.com...
> "fritz steindl \(-:fs\)" <fs at floSoft.net> wrote in message
news:<1020669846.963494 at newsmaster-04.atnet.at>...
> > hi,
> >
> > what is the best way to implement a singleton in python ???
> >
> > ( class that allows only _one_ instantiation - like java singletons)
> >
> > i miss static variables and functions in python (or i don't see them :-)
> >
> > <thx>
> >
> > fritz
> > (-:fs)
>
> I implement a sigleton normally as following:
>
> class DatabaseManager:
>     # Singleton (recycle connections)
>     theConnectionPool = None
>     class __ConnectionPool:
>         def __init__(self):
>             ...
>
>         def getCursor(self, aRecycleFlag = CURSOR_RECYCLE):
>             ...
>
>     def __init__(self):
>         if DatabaseManager.theConnectionPool == None:
>             DatabaseManager.theConnectionPool =
DatabaseManager.__ConnectionPool()
>         else:
>             pass
>
>     def __getattr__(self, aName):
>         return getattr(self.theConnectionPool, aName)
>

While I'm sure the above code does what you want, in strict technical terms
it's neither what the OP asked for, nor a singleton. Multiple instances of
this class can be created, and will have different identities. Of course
they all share the same state (which is what you need in this case), but
that's Borg-like rather than Singleton-like.

regards
 Steve
--
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list