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.

Songtham Tung
Nov 13 · 3 min read
Photo by Annie Spratt on Unsplash

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:

  • Creational
  • Structural
  • Behavioral

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.

https://pixabay.com/illustrations/organization-chart-executive-staff-3558622/

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?

Code

Translating this requirement into Python might look something like this.

Running this will generate the following output:

python3 ceo.py
<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.

That’s it!

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.

Happy coding!

The Startup

Medium's largest active publication, followed by +540K people. Follow to join our community.

Songtham Tung

Written by

Technical Product Director @ Geddit | B2B SaaS | SF ✈️ BKK

The Startup

Medium's largest active publication, followed by +540K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade