Entry
Singleton pattern
Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 314, Chris Tavares
"""
Packages: oop
"""
"""
> I have recently become a Python convert and am enjoying myself
> immensely. Kudo's to Guido!.
>
> I can't seem to figure out how to implement the singleton pattern in
> Python however. It is one of my favorite patterns and I use it
> constantly.
>
> Anybody have any pointers on how to do it?
>
> A short summary of the singleton pattern:
>
> Used when one and only one instance of the object is needed in your app.
> In C++ or java, you hide the constructor as protected (not important).
> The instance is accessed through a static function (typically
> instance()). The first time instance is called, it initializes the
> object with a constructor.
Use a module level function, along with a global variable. Something like
this:
"""
# foo.py:
_fooInstance = None
class _fooClass:
pass
def FooInstance():
global _fooInstance
if _fooInstance is None:
_fooInstance = _fooClass()
return _fooInstance
"""
Users would call foo.FooInstance() to get the singleton object.
"""