1 # Copyright (C) 2010-2012 W. Trevor King <wking@tremily.us>
3 # This file is part of Hooke.
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
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
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/>.
18 """Define the :class:`Singleton` class.
20 >>> class A (Singleton):
22 ... print('initializing instance of {} at ({})'.format(
23 ... self.__class__.__name__, id(self)))
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]))
32 Singletons can also be subclassed.
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]))
42 >>> id(A_instances[0]) == id(B_instances[0])
46 class Singleton (object):
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.
57 Original implementation from Guido van Rossum's
58 `Unifying types and classes in Python 2.2`_.
60 .. Unifying types and classes in Python 2.2:
61 http://www.python.org/download/releases/2.2.3/descrintro/#__new__
63 def __new__(cls, *args, **kwds):
64 it = cls.__dict__.get('__it__')
67 cls.__it__ = it = object.__new__(cls)
68 it.init(*args, **kwds)
71 def init(self, *args, **kwds):