Recipe 6.15. Implementing the "Singleton" Design Pattern
Credit: Jürgen Hermann
Problem
You
want to make sure that only one instance of a class is ever created.
Solution
The _ _new_ _ staticmethod
makes the task very simple:
class Singleton(object):Just have your class inherit from Singleton, and
"" A Pythonic Singleton ""
def _ _new_ _(cls, *args, **kwargs):
if '_inst' not in vars(cls):
cls._inst = type._ _new_ _(cls, *args, **kwargs)
return cls._inst
don't override _ _new_ _. Then,
all calls to that class (normally creations of new instances) return
the same instance. (The instance is created once, on the first such
call to each given subclass of Singleton during each
run of your program.)
Discussion
This recipe shows the one obvious way to implement the
"Singleton" Design Pattern in
Python (see E. Gamma, et al., Design Patterns: Elements of
Reusable Object-Oriented Software, Addison-Wesley). A
Singleton is a class that makes sure only one instance of it is ever
created. Typically, such a class is used to manage resources that by
their nature can exist only once. See Recipe 6.16 for other considerations
about, and alternatives to, the
"Singleton" design pattern in
Python.
We can complete the module with the usual self-test idiom and show
this behavior:
if _ _name_ _ == '_ _main_ _':When we run this module as a script, we get something like the
class SingleSpam(Singleton):
def _ _init_ _(self, s): self.s = s
def _ _str_ _(self): return self.s
s1 = SingleSpam('spam')
print id(s1), s1.spam( )
s2 = SingleSpam('eggs')
print id(s2), s2.spam( )
following output (the exact value of id does vary,
of course):
8172684 spamThe 'eggs' parameter passed when trying to
8172684 spam
instantiate s2 has been ignored, of
coursethat's part of the price you pay for
having a Singleton!One issue with Singleton in general is
subclassability. The way class
Singleton is coded in this recipe, each descendant
subclass, direct or indirect, will get a separate instance. Literally
speaking, this violates the constraint of only one instance
per class, depending on what one exactly means by it:
class Foo(Singleton): passf and b are separate instances,
class Bar(Foo): pass
f = Foo( ); b = Bar( )
print f is b, isinstance(f, Foo), isinstance(b, Foo)
# emits False True True
yet, according to the built-in function
isinstance, they are both
instances of Foo because
isinstance applies the IS-A rule of OOP: an
instance of a subclass IS-An instance of the base class too. On the
other hand, if we took pains to return f again
when b is being instantiated by calling
Bar, we'd be violating the normal
assumption that calling class Bar gives us an
instance of class Bar, not an instance of a random
superclass of Bar that just happens to have been
instantiated earlier in the course of a run of the program.In practice, subclassability of
"Singleton"s
is rather a headache, without any obvious
solution. If this issue is important to you, the alternative
Borg idiom, explained next in Recipe 6.16 may provide a better
approach.
See Also
Recipe 6.16; E. Gamma, R.
Helm, R. Johnson, J. Vlissides, Design Patterns: Elements
of Reusable Object-Oriented Software (Addison-Wesley).