Python and the Singleton Pattern

Neelakantan Krishnaswami neelk at alum.mit.edu
Tue Apr 6 19:12:04 EDT 1999


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




More information about the Python-list mailing list