I\'d like to implement some sort of singleton pattern in my Python program. I was thinking of doing it without using classes; that is, I\'d like to put all the singleton-rel
One approach to implementing a singleton pattern with Python can also be:
have singleton __init()__ method raise an exception if an instance of the class already exists. More precisely, class has a member _single. If this member is different from None, exception is raised.
class Singleton:
__single = None
def __init__( self ):
if Singleton.__single:
raise Singleton.__single
Singleton.__single = self
It could be argued that handling the singleton instance creation with exceptions is not very clean also. We may hide implementation details with a method handle() as in
def Handle( x = Singleton ):
try:
single = x()
except Singleton, s:
single = s
return single
this Handle() method is very similar to what would be a C++ implementation of the Singleton pattern. We could have in Singleton class the handle()
Singleton& Singleton::Handle() {
if( !psingle ) {
psingle = new Singleton;
}
return *psingle;
}
returning either a new Singleton instance or a reference to the existing unique instance of class Singleton.
Handling the whole hierarchy
If Single1 and Single2 classes derive from Singleton, a single instance of Singleton through one of the derived class exists. This can be verify with this:
>>> child = S2( 'singlething' )
>>> junior = Handle( S1)
>>> junior.name()
'singlething'