Singleton Pattern in Python
Make sure a class has exactly one shared instance, such as one settings object or one connection pool.
- The problem Singleton solves
- Implementing it with __new__
- Simpler Python alternatives: modules
- 1
a = AppConfig()First call creates the instance - 2
b = AppConfig()Second call returns the stored one - 3
a is b → TrueSame object
Every call returns the same object
The problem
Some things should exist only once in a program: the app's settings, a connection pool, a logger writing to one file. If every part of the code creates its own copy, settings drift apart and resources are wasted.
Think of it like this
A singleton is like the one school bell in a building. Every classroom rings the same bell; nobody installs a private bell. Asking for "the bell" anywhere always gives you that one bell.
_instance = None🔔 No bell installed yetif cls._instance is None:🔧 Install it the first time someone asksreturn cls._instance🔁 Everyone after that gets the same bellfirst is second✅ Two requests, one object: TrueThe Singleton pattern makes a class return the same single instance every time it is created, giving the program one shared object.
Key points
_instanceis a class attribute that stores the one shared object.__new__is the method Python calls to create an object; it creates the object only when_instanceis still None.cls._instance.theme = "dark"sets up the shared object once.first is secondis True: both names point to the very same object.
When should you use it?
- Application-wide configuration that every module reads.
- One shared resource such as a cache, logger or connection pool.
- Learning how
__new__controls object creation.
When not to use it
- Most Python code: a module-level object (modules are created once) is simpler and does the same job.
- Code you want to test easily: hidden global state makes tests depend on each other; pass the object in instead.
Example code
class AppConfig:
# Singleton: every caller receives one shared configuration object.
_instance = None
def __new__(cls):
# Create the shared instance only on the first call.
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.theme = "dark"
return cls._instance
first = AppConfig()
second = AppConfig()
print(first is second)
Result of running the code
True
Code explanation
__new__ is the method Python calls to create a new object, before __init__. The first time AppConfig() is called, _instance is None, so a real object is created, given its theme and stored on the class. Every later call skips that block and returns the stored object, which is why first is second prints True.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Setting up state in __init__
__init__ runs on every call, so it resets the shared object each time.
def __init__(self):
self.theme = "dark" # runs again for every AppConfig()
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.theme = "dark"
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges