Learn Python
>>> oop_advanced.singleton

The Singleton Pattern in Python

#concept

A singleton is a class deliberately restricted to having exactly one instance for the entire life of a program, with every attempt to create a new one returning that same shared instance instead. It's a common design pattern for things that genuinely should be unique and shared, like a single configuration object or a single connection manager.

#how it works
1

Override __new__(cls)

The method Python actually uses to create a new instance, running before __init__() ever does.

2

Check for an existing instance

Typically stored as a class variable.

3

Return the existing one if present

Instead of building a new object.

4

Create it once if none exists yet

Store it, then return it.

5

Every later call reuses that same object

No matter how many times ClassName() is called.

#example
class Config:
_instance = None
 
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
 
a = Config()
b = Config()
print(a is b)
Output
True
1__new__(cls) runs before __init__(), and checks whether cls._instance has already been set.
2The first call, a = Config(), finds _instance is None, so it creates a genuinely new object and stores it.
3The second call, b = Config(), finds _instance already set from the first call, so it just returns that same existing object instead of building another.
4a is b confirms both names point to the exact same object in memory, proving only one instance was ever truly created.
#use cases
A single shared application configuration object, read from many different parts of a program
A single connection pool or database manager, avoiding the overhead of creating redundant connections
A single logging object that every part of an application writes to consistently
Situations that genuinely need exactly one shared instance, though modules themselves (naturally singleton-like in Python) are often a simpler alternative

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.