Singleton Pattern in Python

Only one instance. Call the constructor twice, get the same object back. People overuse this.

IntermediateObject-Oriented ProgramsExample 23 of 25
singleton-pattern.py
Run in browser
1# Program to implement a simple Singleton pattern
2
3class Singleton:
4 _instance = None
5
6 def __new__(cls, *args, **kwargs):
7 if cls._instance is None:
8 cls._instance = super().__new__(cls)
9 return cls._instance
10
11s1 = Singleton()
12s2 = Singleton()
13
14print(s1 is s2)

Output

True

What's going on

Overriding __new__ ensures that only one instance of Singleton is ever created.