From: neelk at alum.mit.edu (Neelakantan Krishnaswami)
Date: Tue, 06 Apr 1999 23:12:04 GMT
Subject: Python and the Singleton Pattern
References: <slrn7g7d89.33j.gregory.p.green@skorch.rt.cs.boeing.com> <37048D53.5D1ED05F@lemburg.com> <y0jk8vuamz6.fsf@vier.idi.ntnu.no>
Message-ID: <7ee4si$sec$2@antiochus.ultra.net>
Content-Length: 1152
X-UID: 1707                                                  

In article <y0jk8vuamz6.fsf at vier.idi.ntnu.no>, mlh at idt.ntnu.no (Magnus L. Hetland) wrote:
>
>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?

Isn't it possible to make use of Python's dynamism to turn any 
class into a singleton class, as needed?

For example:

class Singletonizer:
    def __init__(self, base_class):
        self.base_class = base_class
        self.obj = None
    def __call__(self, *args, **kw):
        if self.obj is None:
            self.obj = apply(self.base_class, args, kw)
        return self.obj

# Now a test...

class Foo:
    pass

Bar = Singletonizer(Foo)

x = Foo()
y = Foo()

a = Bar()
b = Bar()

if x is not y:
    print "x and y are different objects"

if a is b:
    print "a and b are the same object"

Which yields the right:

x and y are different objects
a and b are the same object

Then you can write your Foo class as usual, and then Singletonize
it as needed. If you are paranoid, you can name Foo "_Foo" so 
that it won't be part of the module's exported interface.


Neel




