Run update-copyright.py.
[hooke.git] / hooke / util / singleton.py
1 # Copyright (C) 2010-2012 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of Hooke.
4 #
5 # Hooke is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU Lesser General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
8 # later version.
9 #
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
13 # details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with Hooke.  If not, see <http://www.gnu.org/licenses/>.
17
18 """Define the :class:`Singleton` class.
19
20 >>> class A (Singleton):
21 ...     def init(self):
22 ...         print 'initializing instance of %s at (%s)' % (
23 ...             self.__class__.__name__, id(self))
24
25 >>> A_instances = [A() for i in range(3)]  # doctest: +ELLIPSIS
26 initializing instance of A at (...)
27 >>> for i in A_instances[1:]:
28 ...     print id(i) == id(A_instances[0])
29 True
30 True
31
32 Singletons can also be subclassed.
33
34 >>> class B (A):
35 ...     pass
36 >>> B_instances = [B() for i in range(3)]  # doctest: +ELLIPSIS
37 initializing instance of B at (...)
38 >>> for i in B_instances[1:]:
39 ...     print id(i) == id(B_instances[0])
40 True
41 True
42 >>> id(A_instances[0]) == id(B_instances[0])
43 False
44 """
45
46 class Singleton (object):
47     """A singleton class.
48
49     To create a singleton class, you subclass from Singleton; each
50     subclass will have a single instance, no matter how many times its
51     constructor is called. To further initialize the subclass
52     instance, subclasses should override 'init' instead of __init__ -
53     the __init__ method is called each time the constructor is called.
54
55     Notes
56     -----
57     Original implementation from Guido van Rossum's
58     `Unifying types and classes in Python 2.2`_.
59
60     .. Unifying types and classes in Python 2.2:
61       http://www.python.org/download/releases/2.2.3/descrintro/#__new__
62     """
63     def __new__(cls, *args, **kwds):
64         it = cls.__dict__.get('__it__')
65         if it is not None:
66             return it
67         cls.__it__ = it = object.__new__(cls)
68         it.init(*args, **kwds)
69         return it
70
71     def init(self, *args, **kwds):
72         pass