dischdennis wrote:
Hello List,
I would like to make a singleton class in python 2.4.3, I found this
pattern in the web:
class Singleton:
__single = None
def __init__( self ):
if Singleton.__single:
raise Singleton.__single
Singleton.__single = self
the line "raise Singleton.__single" invokes in my class the following
error:
exceptions must be classes, instances, or strings (deprecated), not
PurchaseRequisitionController
Greetings, Dennis
The problem is that you yoinked a bad example of a singleton. The
error is correct, only exceptions derived from the Exception class and
strings are supported. (Strings are supported for historical usage,
and a deprecated.)
Why exactly do you need a singleton? Do you want only one instance of
a class? Often, you really want something that shares state: all are
one. This pattern is known as a borg. Please see
"http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531" to see
how the Borg Pattern works.
If you absolutely gotta have a singleton, there are other ways of
implementing it. I can think of only one reason: You want the
singleton's destructor to be called only if there are no remaining
instances in existance. (For the Borg pattern, the deconstructor can
be called once per instance created.)
The problem with this reason is that Python doesn't guarantee when the
destructors will be called for instances (and some instances will never
have their destructors called). Although C-Python implements usually
destroys an instance when its ref-count drops to 0, IronPython and
Jython may do things very differently. (I have no experience with
either of those, so I cannot tell you how they differ.)
Still, if you're dead set on a Singleton class, I'll post one in a
little bit.
--Jason