Python Singleton Design Pattern
In this article, we’ll go over what a singleton pattern is and how to implement it using the example code written in Python.
Design patterns represent the best practices used in software engineering. They are tried and tested solutions to common problems that developers face and can be seen as a guideline to follow.
There are a few categories that make up design patterns:
The singleton design falls into the Creational pattern. As the name implies, this category is used for creating objects. So if the singleton is used to create something, when should I use it? That’s a good question that actually won’t be covered in this article. There are tons of posts on StackOverflow regarding the pros and cons of its usage. Instead, this blog focuses on defining what a singleton is and showing how it might look like in code.
Note that I use Python in this example, but the singleton design pattern can be applied to other programming languages as well.
What’s a Singleton?
In simple terms, the singleton pattern is when only one instance (object) of a class (blueprint) can exist within your app. Wikipedia actually provides a great definition of this.
[Singleton pattern] restricts the instantiation of a class to one “single” instance. This is useful when exactly one object is needed to coordinate actions across the system.
To put it in an analogy, imagine that we are building a software that visualizes the organization chart of a fast-growing tech startup.
For all intents and purposes, let’s assume that there can only be one CEO within the company. How would this requirement look like in code?
Translating this requirement into Python might look something like this.
Running this will generate the following output:
<bound method Ceo.getInstance of <__main__.Ceo object at 0x108d60c50>>
Traceback (most recent call last):
File "ceo.py", line 27, in <module>
createCeoB() # fail
File "ceo.py", line 21, in createCeoB
ceo_b = Ceo()
File "ceo.py", line 11, in __init__
raise Exception("There can only be one CEO. This class is a singleton!")
Exception: There can only be one CEO. This class is a singleton!
As we can see from the logs above, createCeoA() returns the instance object while createCeoB() returns an error. This is the expected output as there can only be one CEO at any given time.
The important idea to note for this design is the __instance variable. Checking this variable when instantiating the class is key for the simpleton pattern. The logic for the constructor __init__ goes as follows:
- If there is no existing CEO, then it will create one.
- Else, it will throw an exception.
The singleton class is a basic design pattern for creating objects that you should understand. If you haven’t done so already, copy and paste the code above and run it straight into your terminal or your favorite IDE.