Singleton?

James T. Dennis jadestar at idiom.com
Sat Jan 26 23:05:04 EST 2002


 Would this be considered to be a valid implementation of 
 the GoF "singleton" pattern?


#!/usr/bin/python2.2
## Singleton "object" in Python?
class Obj: pass
def singleton():
        try:
                return singleton.instance
        except:
                singleton.instance=Obj()
		## instantiate other members
		## and bind any methods here!
                return singleton.instance

if __name__=="__main__":
        a=singleton()
        b=singleton()
        if not a is b:
                raise "Hell"
        else: 
                print "O.K."

 I'm using a function, rather than an object, so that I can
 explicitly return an object reference (which I couldn't do 
 from within a class' __init__ constructor).  In this case
 I'm also using an "empty" object class called "Obj" which 
 is just a generic object with no methods.

 My test suite passes, of course.  But I'm not sure if this
 would count as a valid "singleton" though it does seem to 
 exhibit the desire behavior.  It this "cheating?"  What are
 the consequences of this approach?

 Basically the caller has no reason to know or to care if
 singleton() is a class (and thus he's invoking a normal 
 __init__() constructor with a=singleton()) or whether 
 its a function that returns an object.  I keep looking at
 other "singleton" implementations in Python, and I just don't
 understand why they do things like raise exception or rely on
 oddly named _foo shadow classes, or whatever.

 What am I missing?

 While we're at it; what would be the best resource for 
 reading Python sample implementations of the other GoF OOD 
 Patterns?  Singletons (and Borgs?) keep coming up for discussion,
 but surely people are using Decorators, Adapters, CoRs (chains of
 responsibility), etc?   What might a Python "Flyweight" look like?





More information about the Python-list mailing list