Next / Previous / Contents / TCC Help System / NM Tech homepage

24. class Singleton: Parent class for singletons

This class implements the logic of the Singleton design pattern. It is cribbed directly from Guido van Rossum's document, Unifying types and classes in Python 2.2.

hwscan3.py
# - - - - -   c l a s s   S i n g l e t o n

class Singleton(object):

    def __new__(cls, *args, **kwds):
        it  =  cls.__dict__.get('__it__')
        if it is not None:
            return it
        cls.__it__  =  it  =  object.__new__(cls)
        it.init(*args, **kwds)
        return it

    def init(self, *args, **kwds):
        pass

Inheriting classes should override method init(), not __init__.