Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
Py

Python

Readable, batteries-included, and the default language of AI.

Paradigm
Multi-paradigm, OOP, functional
Typing
Dynamic, strong, optional type hints
Memory
Reference counting + cycle GC
Runs
CPython bytecode interpreter
Concurrency
asyncio, threads (GIL), multiprocessing
Creational pattern

Singleton

Intent

Ensures a class has only one instance and provides a global access point to it.

Problem

Several parts of the app need the same configuration or connection pool, and creating duplicates is wasteful or wrong.

Solution

Make the constructor private and expose a static method that creates the instance once and returns it afterwards.

Real-world analogy

Think of it like this

A country has one official government. Whoever asks for “the government” reaches the same one.

Structure

association / extends implements / depends on
Singleton - instance: Singleton {static}- Singleton()+ getInstance(): Singleton {static} 12 ClientA 3 ClientB

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Singleton — Singleton keeps a private static instance and a private constructor, so nobody else can create it.
  2. 2Singleton — getInstance() creates the instance on the first call and returns the same one afterwards.
  3. 3ClientA — Clients call getInstance() and always receive the same object.

Try it

InteractiveAsk for the config from different clients. Turn the pattern off to see the difference.
0instances created
Clients ask for the config
// calls appear here

Code example

singleton.py
class Config:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.values = {"env": "dev"}
        return cls._instance

assert Config() is Config()

# More Pythonic: modules are imported once, so a module-level object is already a singleton.
# config.py  ->  config = Config()

Applicability

Use Singleton when exactly one instance must exist (shared config, a single pool).

Use Singleton when you need stricter control than global variables.

How to implement

  1. Add a private static field for the instance
  2. Declare a public static creation method
  3. Implement lazy initialisation, thread-safe if needed
  4. Make the constructor private
  5. Replace direct construction with calls to the static method

Pros and cons

Pros

  • Guaranteed single instance
  • Lazy initialisation

Cons

  • Violates Single Responsibility (manages its lifetime and does work)
  • Hides dependencies and complicates unit tests
  • Needs care in multithreaded code
  • Often better replaced by a DI container singleton lifetime

Relations with other patterns

Check yourself

Check yourself

All modules must share one in-memory cache instance, created lazily on first use.

Saved in this browser only. Part of Creational patterns (0/5), Hands-on: patterns with live demos (0/5).