26a657e728c435c87dfcef849c3f4c695866bdc7
[hooke.git] / hooke / util / singleton.py
1 # Copyright
2
3 """Define the :class:`Singleton` class.
4
5 >>> class A (Singleton):
6 ...     def init(self):
7 ...         print 'initializing instance of %s at (%s)' % (
8 ...             self.__class__.__name__, id(self))
9
10 >>> A_instances = [A() for i in range(3)]  # doctest: +ELLIPSIS
11 initializing instance of A at (...)
12 >>> for i in A_instances[1:]:
13 ...     print id(i) == id(A_instances[0])
14 True
15 True
16
17 Singletons can also be subclassed.
18
19 >>> class B (A):
20 ...     pass
21 >>> B_instances = [B() for i in range(3)]  # doctest: +ELLIPSIS
22 initializing instance of B at (...)
23 >>> for i in B_instances[1:]:
24 ...     print id(i) == id(B_instances[0])
25 True
26 True
27 >>> id(A_instances[0]) == id(B_instances[0])
28 False
29 """
30
31 class Singleton (object):
32     """A singleton class.
33
34     To create a singleton class, you subclass from Singleton; each
35     subclass will have a single instance, no matter how many times its
36     constructor is called. To further initialize the subclass
37     instance, subclasses should override 'init' instead of __init__ -
38     the __init__ method is called each time the constructor is called.
39
40     Notes
41     -----
42     Original implementation from Guido van Rossum's
43     `Unifying types and classes in Python 2.2`_.
44
45     .. Unifying types and classes in Python 2.2:
46       http://www.python.org/download/releases/2.2.3/descrintro/#__new__
47     """
48     def __new__(cls, *args, **kwds):
49         it = cls.__dict__.get('__it__')
50         if it is not None:
51             return it
52         cls.__it__ = it = object.__new__(cls)
53         it.init(*args, **kwds)
54         return it
55
56     def init(self, *args, **kwds):
57         pass