PythonMastery

Singleton pattern in Python

Make a class that can only ever have one object, using __new__. Shows the __init__ problem, and why a module is often the simpler choice.

A singleton is a class that has only one object. Every time you call the class, you get that same object back. It is used for things the whole program should share, such as one settings object or one connection pool.

The program

python
class Settings:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.values = {"theme": "light"}  # set up only once
        return cls._instance


a = Settings()
b = Settings()

a.values["theme"] = "dark"

print(a is b)
print(b.values["theme"])
output
True
dark

How it works

The __init__ problem

python
class Settings:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        self.values = {"theme": "light"}


a = Settings()
a.values["theme"] = "dark"
b = Settings()  # runs __init__ again
print(a.values["theme"])
output
light

A simpler way: a module

A Python module is loaded only once. Every import settings in the program gets the same module object. So a module with variables at the top level already behaves like a singleton:

python
# settings.py
theme = "light"

Any file can then use import settings and settings.theme = "dark", and every other file sees the change. Many Python programmers prefer this to a singleton class, because it needs no extra code.

Learn the idea: Design Patterns That Fit Python, Object-Oriented Programming