11.6 The Singleton pattern
The Singleton pattern is a source of some controversy; many have accused it of being an anti-pattern, a pattern that should be avoided, not promoted. In Python, if someone is using the Singleton pattern, they’re almost certainly doing something wrong, probably because they’re coming from a more restrictive programming language.
So, why discuss it at all? The basic idea behind the Singleton pattern is to allow exactly one instance of a certain object to exist. A Python example of this is the None object, the one — and only — instance of the NoneType.
Generally, when a singleton class is used, each collaborator requests an instance of the class. The class makes sure that the one-and-only instance is always returned. The UML diagram doesn’t fully describe it, but here it is for completeness:
In some OO programming environments...