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?

4 of 9 people (44%) answered Yes
Recently 1 of 6 people (17%) answered Yes

Entry

Python and the Singleton Pattern

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 89, Magnus L. Hetland


"""
Packages: oop
"""
"""
> 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()
Hm... That's nice :)
But isn't the point that people should be able to use the singleton
instantiator without knowing if it already has been instantiated, and
always get the same instance?
Even though I think my previous version is more intuitive -- what
about this:
"""
class MySingleton:
    def __init__(self):
        # Do something
        pass
    def __call__(self):
        return self
MySingleton = MySingleton()
"""
We are moving away from the standard singleton here, but I guess it
could still be used -- as could yours, if one doesn't try to
instantiate it, only use it as a singleton instance... (But then what use
is the pattern, anyway, if it is reduced to a single globally accessible
variable... ;)
"""