faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 3 people (100%) answered Yes
Recently 1 of 1 people (100%) answered Yes

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()