Singleton

Singleton (GoF Creational) — and the Pythonic alternatives

"Singletons are pathological liars." — Misko Hevery (creator of AngularJS) on testing Singletons

"Modules in Python are singletons. There is no need to write your own." — Python community folklore (several wordings, collective authorship)


What GoF says

"Ensure a class has only one instance, and provide a global point of access to it."

That sentence is the source of all the problems. It mixes two ideas that should be separated:

  1. "Only one instance" is sometimes justified (a hardware resource, a connection pool).
  2. "Global point of access" is almost always an anti-pattern.

The classic Singleton fuses both into one implementation, and the global access is what pollutes the architecture.


The classic form (anti-pattern)

class Database:
    _instance = None

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

    def connect(self, url: str):
        self._url = url

    def execute(self, sql: str):
        return f"executing {sql} on {self._url}"


# Everywhere in the code:
db = Database()                                    # ← always the same one
db.connect("postgres://...")

# In another file:
db2 = Database()
db2.execute("SELECT ...")                          # works, because it is the same

Looks convenient. It is also a hidden global variable.


Five reasons Singleton is an anti-pattern

1. Hidden global state

class UserRepository:
    def get(self, user_id):
        db = Database()                            # ← dependency invisible in the signature!
        return db.execute(f"SELECT * FROM users WHERE id={user_id}")

Looking at UserRepository.__init__(), you cannot see that the class depends on Database. The dependency is hidden in the method body.

A DIP failure. High-level (business logic) depends directly on low-level (DB), not through an abstraction.

2. Tests become fragile

def test_user_repository():
    repo = UserRepository()
    user = repo.get(42)                            # ← calls the REAL DB
    ...

How do you swap in a fake? You cannot. Singleton does not let you replace the implementation.

The workaround is monkey-patching:

def test_user_repository(monkeypatch):
    fake_db = FakeDatabase()
    monkeypatch.setattr("module.Database._instance", fake_db)

This violates:

3. Race condition in __new__

def __new__(cls):
    if cls._instance is None:        # ← T1 and T2 both see None
        cls._instance = super().__new__(cls)
    return cls._instance

Two threads → two instances. A classic race. The fix is a threading.Lock, but that is more complexity for a pattern that is already complex.

4. Initialisation order — undefined

db = Database()
db.connect("postgres://...")    # when do you call this?

# In another module:
repo = UserRepository()
repo.get(42)                     # if connect was not called yet, bug!

Team discipline instead of a type guarantee. The more Singletons you have, the harder "the correct initialisation order" gets.

5. Inheritance does not behave well

class SpecialDatabase(Database):
    ...

db1 = Database()
db2 = SpecialDatabase()
# What type is db2? Same as db1? A separate one?
# Depends on the Singleton implementation, and the answer is often surprising.

Pythonic alternatives

1. Module as Singleton (the standard)

Python modules are already singletons:

# config.py
import os

DATABASE_URL = os.environ["DATABASE_URL"]
DEBUG = os.environ.get("DEBUG") == "1"
MAX_CONNECTIONS = int(os.environ.get("MAX_CONNECTIONS", "10"))
# anywhere.py
from config import DATABASE_URL, DEBUG

That is a singleton. No class, no __new__, no race.

Good for: config, constants, version info, environment-based settings.

2. Dependency Injection (for most objects)

Instead of a Singleton, create one instance in the Composition Root and pass it around:

# main.py — Composition Root
def main():
    db = Database(url="postgres://...")          # ← ONE instance, explicit
    user_repo = UserRepository(db=db)             # ← inject it
    order_repo = OrderRepository(db=db)           # ← the same instance

    service = OrderService(user_repo, order_repo)
    service.process_order(...)

Same effect (one instance per program), but:

Good for: anything with a lifecycle (connections, services, repositories, gateways).

3. @functools.cache on a factory (a lazy singleton without a class)

When you need a lazy singleton — created on first access:

from functools import cache

@cache                                              # ← Python 3.9+
def get_settings() -> Settings:
    return Settings.load_from_env()


# Everywhere in the code:
settings = get_settings()                          # first call creates it
settings = get_settings()                          # the rest return the cached one

@cache (or @lru_cache(maxsize=None)) remembers the result by arguments (for a no-argument function, one result forever).

Good for: lazy-loaded config, heavy objects, FastAPI Depends() providers.

4. A class as a namespace (no instances)

class HttpStatus:
    OK = 200
    NOT_FOUND = 404
    INTERNAL_SERVER_ERROR = 500


code = HttpStatus.OK

This is not a Singleton, just a group of constants. A classic alternative to Java, where enum would be the cover. In Python it is just a class with class-level attributes.

Good for: constants, enumerations (although enum.Enum is better for those).


When Singleton may be justified

Rare cases:

1. Access to physical hardware

There really is one physical resource, and global access is part of the model.

2. Connection or thread pools at the library level

Some libraries have internal singletons (for example, requests.Session by default). These are library implementation details, not your code.

3. Old Java APIs you are porting

If you are rewriting Java code in Python, leaving a Singleton temporarily is pragmatic. Refactor to DI later.

If your project has more than two Singletons, suspect you took a wrong turn.


"Borg pattern" — a lesser-known alternative

(Alex Martelli, ActiveState Cookbook recipe 66531, 2001. The name is a Star Trek reference: "Resistance is futile, you will be assimilated" — all instances "assimilate" into the same state.)

Instead of "one instance, many calls", you have many instances, shared state:

class Borg:
    _shared_state = {}

    def __init__(self):
        self.__dict__ = self._shared_state          # ← all instances share __dict__


class MyConfig(Borg):
    def __init__(self):
        super().__init__()
        if not hasattr(self, "loaded"):
            self.config = load_config()
            self.loaded = True

Interesting, but rarely appropriate. It has the same testing problems as Singleton. Mentioned here for completeness.


How to spot a Singleton in someone else's code

Markers:

  1. _instance as a class-level attribute.
  2. __new__ with "if None" logic.
  3. A @singleton decorator (custom).
  4. A SingletonMeta metaclass.
  5. A module-level _instance = SomeClass() with a lazy getter.

Any of these is a signal to ask: "could we do DI here instead of a Singleton?"


Anti-patterns when refactoring Singleton → DI

1. "Pseudo-DI" that takes a Singleton as a parameter

class UserRepository:
    def __init__(self, db: Database):
        self._db = db

# Somewhere in the code:
repo = UserRepository(db=Database())              # ← still a global!

If Database is a Singleton, passing it through is cosmetic. You need to:

  1. Make Database a plain class without Singleton logic.
  2. Create one instance in main().
  3. Pass it into UserRepository.

2. Turning Singleton into "conditional"

class Database:
    def __new__(cls):
        if not testing_mode():                     # ← checking the environment!
            ...

This does not fix the problem, it makes it worse. The race comes back, and now there are two implementations that behave differently.

3. Importing a Singleton into the business logic

from app.database import db_singleton

class UserService:
    def get(self, id):
        return db_singleton.execute(...)          # ← global in the business layer

This is exactly what DIP is trying to avoid. Inject db through the constructor instead.


Rules of thumb

  1. "One instance" ≠ "global access". The first is achieved through DI or caching. The second is the anti-pattern.
  2. Modules are singletons by design. If you need "one per process", plain module-level state can be ideal.
  3. A lazy singleton without a class is @cache on a factory. Clean and Pythonic.
  4. DI beats Singleton almost always. Exceptions are hardware resources.
  5. _instance as a class attribute is an anti-pattern marker. Rewrite it.
  6. A @singleton decorator from PyPI is something to be embarrassed about.
  7. Testability is the final criterion. If your Singleton is hard to test, that is the signal.

One-line summary

Do not write Singleton. Use a module as a singleton (for constants), @cache on a factory (for lazy unique objects), or DI (for everything else). The classic Singleton is global state in a ritual costume.