Skip to content

Singleton Pattern - Exactly One Instance

Updated: at 12:00 AM

1. The Problem

Problem: A Resource That Must Exist Exactly Once

Some objects represent global system resources where multiple instances are incorrect or dangerous.

Examples:

If multiple instances are created:

Naive code makes this easy to break:

config1 = Config()
config2 = Config()  # Oops — different instance

We need exactly one instance, shared across the system, with controlled creation.

2. The Singleton Pattern: Controlled Global State

The Singleton Pattern solves this by:

Core idea:

There is exactly one instance, and everyone talks to the same one.

A Singleton has three properties:

  1. Private construction – cannot be freely instantiated
  2. Single stored instance – created once
  3. Global access method – returns that instance

Use Singleton when:

3. Implementation: Singleton in Python

Example: Application Configuration

Goal: One configuration object shared everywhere.

Basic Singleton (Lazy Initialization)

class AppConfig:
    _instance = None

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

    def _load(self):
        self.debug = True
        self.db_url = "postgres://localhost"

Usage:

config1 = AppConfig()
config2 = AppConfig()

assert config1 is config2  # Same instance

Thread-Safe Singleton

For multi-threaded environments:

import threading

class AppConfig:
    _instance = None
    _lock = threading.Lock()

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

    def _load(self):
        self.debug = True

This guarantees:

4. When to Use Singleton (and When Not To)

Use Singleton when:

Avoid Singleton when:

Common pitfalls:

5. Singleton vs Alternatives

NeedBetter Option
Shared logicStatic functions
Shared immutable dataConstants / config objects
Shared mutable stateSingleton
Test-friendly designDependency Injection

Singleton is not about convenience. It is about correctness under constraint.

Use it only when the domain demands one — and only one — instance.