Entry
Singleton pattern
Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 312, M.-A. Lemburg
"""
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.
Here is a very simple but effective version:
"""
class MySingleton:
def __init__(self):
# Init the singleton
pass
# Instantiate once, overwriting the previous name binding.
MySingleton = MySingleton()
# Try to instantiate it again (this will give an error):
AnotherSingleton = MySingleton()