8
The Singleton Pattern
The Singleton pattern is grouped with the other creational patterns, although, to some extent, it is a “noncreational” pattern. There are any number of cases in programming where you need to make sure that there can be one, and only one, instance of a class. For example, your system can have only one window manager or print spooler, as well as a single point of access to a database engine.
Python does not directly have a feature where a single static variable will be accessible from all class instances, so a simple flag won’t work. Instead, this technique utilizes two subtle Python features you might not be aware of: the static method and the __instance variable.
Python has a Decorator that tells the compiler to make ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access