Singleton Classes

You may sometime need to create classes that can only be instantiated once. There are many ways to create these so-called "Singleton" classes. Refer to this site and also for example code. One way not mentioned in these links (code is from here) is:

class MySingleton:
    def __init__(self):
        # Do something
        pass
    def __call__(self):
        return self

MySingleton = MySingleton() </verbatim>

-- EdmundLian - 21 Jan 2002

Note that all these singleton ideas are equivalent to a module-level global -- the only advantage is that they allow using a class-like syntax. Like a module-level global, if you have ambiguities in your path such that a module is imported twice, the object will not be a true singleton. Also, like a global, you must be particularly careful about thread-safety.

Singleton's are in some ways a case of using a factory: that is, instead of normal class instantiation, you use something that looks like instantiation but may return an already-created object. I've written a small class that assists in creating factories: ParamFactory.py -- useful for the case when you have an external ID (e.g., a username), and you want to be sure you create only one object for each ID.

-- IanBicking - 21 Jan 2002