The singleton design pattern in Python makes sure a class only ever has one instance, and every call hands back that same object. The quickest version overrides __new__ to store and reuse the instance:
class AppConfig:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
Each implementation below ran on Python 3.12.5, and I checked the “same object” claim with is every time.
We’ll start with the simplest Pythonic option, then cover __new__, a metaclass, a decorator, thread safety, and when you shouldn’t use a singleton at all.
The Pythonic singleton: a module
Python imports a module once and caches it in sys.modules, so a module is already a singleton. Put your shared state in config.py and import it wherever you need it:
# config.py
TAX_RATE = 0.0825
CURRENCY = "USD"
# anywhere else
import config
print(config.CURRENCY)
If you don’t need a class, this is the approach I’d pick. There’s no pattern code to maintain, and anyone reading it understands it.
Singleton with __new__ (and its catch)
__new__ creates the object, so returning the stored instance makes every call share it. The catch is that __init__ still runs on every call:
class AppConfig:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, region="us-east"):
print(f" __init__ runs, region={region}")
self.region = region
a = AppConfig("us-east")
b = AppConfig("us-west") # same object, but __init__ runs again!
print(a is b, id(a) == id(b))
print("a.region is now", a.region)
Output:
__init__ runs, region=us-east
__init__ runs, region=us-west
True True
a.region is now us-west

__init__ overwrote the region with us-west.Either guard __init__ with a flag, or use the metaclass version below, which skips __init__ after the first call.
Singleton design pattern in Python with a metaclass
A metaclass controls what happens when you call the class, so it can return the cached instance before __init__ runs again. It’s reusable across classes too:
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs) # __init__ runs only once
return cls._instances[cls]
class Database(metaclass=SingletonMeta):
def __init__(self, url):
print(" connecting to", url)
self.url = url
class Logger(metaclass=SingletonMeta):
def __init__(self):
self.lines = []
db1 = Database("postgres://orders.example.com/sales")
db2 = Database("postgres://other.example.com/test")
print(db1 is db2, db2.url)
print(Logger() is Logger(), Logger() is db1)
Output:
connecting to postgres://orders.example.com/sales
True postgres://orders.example.com/sales
True False

This is the version most tutorials call “the” singleton. If metaclasses are new to you, the factory design pattern in Python is a gentler introduction to object-creation patterns.
Singleton with a decorator
A class decorator keeps the singleton logic out of the class body. It’s tidy, but the name now points to a function, not the class:
from functools import wraps
def singleton(cls):
instances = {}
@wraps(cls)
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class PaymentGateway:
def __init__(self, currency="USD"):
self.currency = currency
g1 = PaymentGateway()
g2 = PaymentGateway("EUR") # ignored: the instance already exists
print(g1 is g2, g2.currency, type(g1).__name__)
Output:
True USD PaymentGateway
That means isinstance(g1, PaymentGateway) fails, which is why I prefer the metaclass. Decorators themselves are explained in higher order functions in Python.
Is the singleton pattern thread-safe in Python?
Not automatically. Two threads can both see _instance is None and each build an object. A lock with a second check inside it fixes the race:
import threading
import time
class Unsafe:
_instance = None
def __new__(cls):
if cls._instance is None:
time.sleep(0.01) # widen the race window so it shows up
cls._instance = super().__new__(cls)
return cls._instance
class Safe:
_instance = None
_lock = threading.Lock()
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None: # check again inside the lock
time.sleep(0.01)
cls._instance = super().__new__(cls)
return cls._instance
for cls in (Unsafe, Safe):
ids = set()
threads = [threading.Thread(target=lambda: ids.add(id(cls()))) for _ in range(8)]
for t in threads: t.start()
for t in threads: t.join()
print(f"{cls.__name__:<7} 8 threads -> {len(ids)} different instance(s)")
Output:
Unsafe 8 threads -> 2 different instance(s)
Safe 8 threads -> 1 different instance(s)

The short sleep just makes the race easy to see. In real code the window is smaller, but it’s still there, especially when creating the object is slow.
A simpler alternative: functools.cache
You often don’t need a singleton class at all; you just need one shared object. Caching a getter function gives you exactly that:
from functools import cache
class Settings:
def __init__(self):
print(" loading settings once")
self.tax_rate = 0.0825
self.currency = "USD"
@cache
def get_settings():
return Settings()
print(get_settings() is get_settings())
print(get_settings().currency, get_settings().tax_rate)
Output:
loading settings once
True
USD 0.0825

This keeps Settings a normal class you can still create directly in tests, which is a real advantage.
When should you use a singleton?
| Good fit | Think twice |
|---|---|
| App-wide configuration | Anything you’ll need two of in tests |
| A shared connection pool or logger | Hiding dependencies that should be passed in |
| Caching an expensive object | Mutable global state many parts of code change |
Singletons are global state in disguise, which makes testing harder. Passing the object in as an argument is often cleaner.
More Python design and class guides:
Frequently asked questions
What is the singleton design pattern in Python?
It restricts a class to one instance and returns that same object every time the class is called.
What’s the best way to make a singleton in Python?
Often a module or a cached getter. If you need a class, a metaclass is the most robust because __init__ only runs once.
Why does __init__ run every time in my singleton?
Overriding __new__ returns the same object, but Python still calls __init__ on it. Use a metaclass or guard __init__.
Is a Python singleton thread-safe?
Not by default. Use a threading.Lock and check for the instance again inside the lock.
Are singletons bad practice?
They’re global state, which can make testing harder. Use them sparingly, for things like configuration or connection pools.
Where is __new__ documented?
See object.__new__ in the Python data model docs.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn