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