Sitemap

Singleton Design Pattern

3 min readFeb 28, 2026

--

Singleton means a class which can only be instantiate once. If we again try to instantiate the class it will just return us the earlier object.

Singleton design pattern is used to implement singleton class.

Introduction

Without implementing singleton pattern the code will look like this:

class NoSingleton:
def __init__(self):
print("Singleton Constructor called. New Object created.")


if __name__ == "__main__":
s1 = NoSingleton()
s2 = NoSingleton()

print(s1 is s2)

Output

Singleton Constructor called. New Object created.
Singleton Constructor called. New Object created.
False

In the above example we can see 2 different objects being created. We can implement a simple singleton code by making the constructor private (note that is python there is no concept of a private constructor)

class Singleton:
_instance = None # Initialize static member
_initialized = False # Guard to mimic private constructor

# It is always public — we manually guard it with a flag
def __init__(self):
if not Singleton._initialized:
raise RuntimeError("Constructor is private. Use get_instance() instead.") # mimicking private constructor behavior
print("Singleton Constructor called")

# @classmethod + cls parameter : for static methods
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._initialized = True
cls._instance = Singleton()
cls._initialized = False
return cls._instance


if __name__ == "__main__":
s1 = Singleton.get_instance()
s2 = Singleton.get_instance()

print(s1 is s2)

# Trying to create a new instance directly will raise an error
# s3 = Singleton() # RuntimeError: Constructor is private. Use get_instance() instead.

Output

Singleton Constructor called
True

The problem is that the above code is not thread safe. To make it thread safe we make it like below code.

import threading


class Singleton:
_instance = None
_lock = threading.Lock()
_initialized = False


def __init__(self):
if not Singleton._initialized:
raise RuntimeError("Constructor is private. Use get_instance() instead.")
print("Singleton Constructor Called!")


@classmethod
def get_instance(cls):
with cls._lock:
if cls._instance is None:
cls._initialized = True
cls._instance = Singleton()
cls._initialized = False
return cls._instance

if __name__ == "__main__":
s1 = Singleton.get_instance()
s2 = Singleton.get_instance()

print(s1 is s2)


# This aproach is resource heavy because we have to hold the resource whenever the function is called

Output

Singleton Constructor Called!
True

Problem: The above aproach is resource heavy because we have to hold the resource whenever the method is called.

Get Irfan’s stories in your inbox

Join Medium for free to get updates from this writer.

To solve this problem we use locks.

import threading


class Singleton:
_instance = None
_lock = threading.Lock()
_initialized = False

def __init__(self):
if not Singleton._initialized:
raise RuntimeError("Constructor is private. Use get_instance() instead.")
print("Singleton Constructor Called!")

# Double check locking..
@classmethod
def get_instance(cls):
if cls._instance is None: # First check (no locking)
with cls._lock: # Lock only if needed
if cls._instance is None: # Second check (after acquiring lock)
cls._initialized = True
cls._instance = Singleton()
cls._initialized = False
return cls._instance


if __name__ == "__main__":
s1 = Singleton.get_instance()
s2 = Singleton.get_instance()

print(s1 is s2)

Output

Singleton Constructor Called!
True

Another way to solve the problem without using locks is to do eager initialisation.

class Singleton:
_initialized = False

def __init__(self):
if not Singleton._initialized:
raise RuntimeError("Constructor is private. Use get_instance() instead.")
print("Singleton Constructor Called!")

@classmethod
def get_instance(cls):
return cls._instance


# Initialize static members — eagerly create the instance at class load time
Singleton._initialized = True
Singleton._instance = Singleton()
Singleton._initialized = False


if __name__ == "__main__":
s1 = Singleton.get_instance()
s2 = Singleton.get_instance()

print(s1 is s2)


# Pros: simple to implement
# Cons: if the object initialisation is resource heavy and it is not used after initialization then it is waste of resource, so this approach can only be suitable for light weight objects

Output

Singleton Constructor Called!
True

Pros: simple to implement

Cons: if the object initialisation is resource heavy and it is not used after initialization then it is waste of resource, so this approach can only be suitable for light weight objects.

Practical Usecase

  1. Logging system
  2. Database connection
  3. Configuration Manager

In all these examples we only need one instance of the class.

Thank you for reading the blog. In our next blog we will be learning about build a LLD diagram of a food delivery app.

Credits: Aditya Tandon

--

--

Irfan
Irfan

Written by Irfan

Full-Stack Mobile Developer