In Python, the Singleton Pattern is a design pattern that ensures a class has only one instance (object) throughout the entire program.
No matter how many times you try to create an object, Python will always return the same instance.
🔹 What is a Singleton Class?
A Singleton Class is:
A class that allows only one object to be created and provides a global point of access to it.
🔹 Why Use Singleton Class?
Singleton is useful when you need:
- ✔ One shared resource across the program
- ✔ Global configuration settings
- ✔ Database connection manager
- ✔ Logging system
- ✔ Cache management
🔹 Real-Life Example
Think about:
- 🖨 Printer spooler → only one system should manage printing
- 🗄 Database connection → reuse same connection
- ⚙ Configuration manager → single settings file
🔹 How Singleton Works in Python
Python allows multiple ways to create Singleton classes:
-
Using
__new__()method - Using decorators
- Using modules (natural singleton)
We will learn the most important methods.
🔹 1. Singleton Using __new__() Method
This is the most common and clean approach.
Example:
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
Testing Singleton:
obj1 = Singleton()
obj2 = Singleton()
print(obj1)
print(obj2)
print(obj1 is obj2)
Output:
<__main__.Singleton object at 0x...>
<__main__.Singleton object at 0x...>
True
👉 Both objects are the same instance
🔹 2. Singleton Using Class Variable
class Database:
instance = None
def __init__(self):
if Database.instance is not None:
raise Exception("This class is a Singleton!")
Database.instance = self
Usage:
db1 = Database()
# db2 = Database() ❌ Will raise error
🔹 3. Singleton Using Decorator
Python decorators can also enforce Singleton behavior.
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
Apply decorator:
@singleton
class Logger:
def __init__(self):
self.logs = []
Test:
l1 = Logger()
l2 = Logger()
print(l1 is l2)
Output:
True
🔹 4. Singleton Using Module (Best Simple Way)
In Python, modules are naturally singleton.
Example:
# config.py
value = 100
Usage:
import config
print(config.value)
👉 No matter how many times you import it, only one instance exists.
🔹 5. Real-Life Singleton Example (Logger System)
class Logger:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Logger, cls).__new__(cls)
cls._instance.logs = []
return cls._instance
def log(self, message):
self.logs.append(message)
Usage:
log1 = Logger()
log2 = Logger()
log1.log("Error occurred")
log2.log("System running")
print(log1.logs)
print(log1 is log2)
🔹 Output:
['Error occurred', 'System running']
True
🔹 Advantages of Singleton Pattern
✅ 1. Controlled access
Only one instance exists.
✅ 2. Saves memory
No duplicate objects.
✅ 3. Global access point
Easy to use shared resources.
✅ 4. Consistent data
Same state everywhere in program.
🔹 Disadvantages of Singleton
❌ 1. Global state issues
❌ 2. Hard to test in unit testing
❌ 3. Can create hidden dependencies
❌ 4. Not always needed
🔹 Singleton vs Normal Class
| Feature | Singleton Class | Normal Class |
|---|---|---|
| Instances | Only one | Multiple |
| Memory usage | Low | Higher |
| Use case | Shared resources | General objects |
| Flexibility | Limited | High |
🔹 When to Use Singleton?
Use Singleton when:
- Database connection manager
- Logging system
- Configuration manager
- Cache system
- Hardware interface control
🔹 When NOT to Use Singleton
Avoid Singleton when:
- You need multiple independent objects
- You are writing simple applications
- You want better testability
🚀 Conclusion
The Singleton Pattern in Python ensures that a class has only one instance and provides a global access point to it.
It is widely used in:
- System design
- Backend applications
- Logging systems
- Database connections
However, it should be used carefully because overusing Singleton can make code harder to maintain.


0 Comments