Singleton pattern
The Singleton pattern is a design pattern that restricts a class to having only one instance and provides a single point of access to it. This is useful when you only need one instance of a class to control the action throughout the execution of a program.
Get Vivek Pradhan’s stories in your inbox
Join Medium for free to get updates from this writer.
To implement the Singleton pattern in Python, you can follow these steps:
- Define a class with the
__new__method overridden to ensure that only one instance of the class can be created.
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance2. Add the instance attributes and methods to the class as desired.
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
def some_business_logic(self):
# implementation of business logic
pass- To use the singleton class, simply create an instance of it:
s = Singleton()
s.some_business_logic()Note: In Python, the singleton pattern can also be implemented by using metaclasses, but the above approach is the most common one.








