Sitemap

Singleton Design Pattern — Python Example

3 min readMay 23, 2026

--

Press enter or click to view image in full size

1. Intent of Singleton

The Singleton pattern ensures:

“A class has only one instance and provides a global access point to it.”

This means:

  • Only one object of the class can ever exist
  • Everyone uses the same shared instance

2. Why Do We Need Singleton?

Imagine these scenarios:

  • Database connection manager
  • Logger service
  • Cache manager
  • Configuration manager
  • Thread pool manager
  • Application-wide settings
  • GPU resource manager

You typically want:

  • centralized control
  • shared state
  • resource optimization

You do NOT want:

  • multiple DB pools accidentally created
  • multiple logger files writing independently
  • duplicated cache state

3. Basic Singleton Implementation in Python

class Singleton:
_instance = None

def __new__(cls):
if cls._instance is None:
print("Creating new instance")
cls._instance = super().__new__(cls)

return cls._instance

obj1 = Singleton()
obj2 = Singleton()

print(obj1 is obj2) # True

4. Understanding __new__

In Python:

Get Pulkit Arora’s stories in your inbox

Join Medium for free to get updates from this writer.

__new__ is responsible for:

  • creating object

__init__ is responsible for:

  • initializing object

Singleton mainly controls:

  • object creation

Therefore:

  • we override __new__

5. Better Singleton

class Singleton:
_instance = None
_initialized = False

def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)

return cls._instance

def __init__(self):
if not self._initialized:
print("Initializing once")
self.value = 100
Singleton._initialized = True

6. Production-Level Example — Logger

class Logger:
_instance = None

def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.logs = []

return cls._instance

def log(self, message):
self.logs.append(message)

def show_logs(self):
for log in self.logs:
print(log)

logger1 = Logger()
logger2 = Logger()

logger1.log("Started app")
logger2.log("DB connected")

logger1.show_logs()


# Output
Started app
DB connected

Both share:

  • same state
  • same object

7. Thread-Safe Singleton

# Use Locking

import threading

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

def __new__(cls):

if cls._instance is None:

with cls._lock:

if cls._instance is None:
cls._instance = super().__new__(cls)

return cls._instance

# Used in: high-concurrency systems

8. Singleton Using Metaclass

class SingletonMeta(type):

_instances = {}

def __call__(cls, *args, **kwargs):

if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)

return cls._instances[cls]

# Usage

class Database(metaclass=SingletonMeta):

def connect(self):
print("Connected")

d1 = Database()
d2 = Database()

print(d1 is d2) # True

9. Why Metaclass Version is Better

Benefits:

  • reusable
  • cleaner
  • scalable
  • supports multiple singleton classes
  • separates singleton logic

This is closer to:

  • framework-level engineering

10. When to Use Singleton

Use when:

  • exactly one logical instance should exist
  • shared coordination required
  • expensive resource initialization
  • application-wide shared service

Good candidates:

  • logging
  • config manager
  • DB connection pool manager
  • cache manager

11. When NOT to Use Singleton

Avoid when:

  • state changes frequently
  • unit testing is critical
  • dependency injection already solves problem
  • object uniqueness isn’t mandatory
  • scalability/distributed systems involved

12. Most Pythonic Production Version

import threading

class SingletonMeta(type):

_instances = {}
_lock = threading.Lock()

def __call__(cls, *args, **kwargs):

if cls not in cls._instances:

with cls._lock:

if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance

return cls._instances[cls]


class Database(metaclass=SingletonMeta):

def __init__(self):
self.connection = "Connected"

def query(self):
print("Executing query")


# Usage

db1 = Database()
db2 = Database()

print(db1 is db2)

Thanks for Reading!

I’m passionate about backend engineering, scalable systems, and writing clean, maintainable software.

If this article helped you, feel free to connect with me on LinkedIn. I’m always open to networking with fellow engineers, tech enthusiasts.

See you in the next article 🚀

--

--