Python Design Patterns

Singleton Pattern in Python

Make sure a class has exactly one shared instance, such as one settings object or one connection pool.

  • Advanced
  • 2 min read
  • 1 runnable example
What you'll learn
  • The problem Singleton solves
  • Implementing it with __new__
  • Simpler Python alternatives: modules
AppConfig() twice
  1. 1a = AppConfig()First call creates the instance
  2. 2b = AppConfig()Second call returns the stored one
  3. 3a is b → TrueSame object

Every call returns the same object

The problem

Some things should exist only once in a program: the app's settings, a connection pool, a logger writing to one file. If every part of the code creates its own copy, settings drift apart and resources are wasted.

Think of it like this

A singleton is like the one school bell in a building. Every classroom rings the same bell; nobody installs a private bell. Asking for "the bell" anywhere always gives you that one bell.

From the school bell to code
_instance = None🔔 No bell installed yet
if cls._instance is None:🔧 Install it the first time someone asks
return cls._instance🔁 Everyone after that gets the same bell
first is second✅ Two requests, one object: True
Every call returns the same object.
In one sentence

The Singleton pattern makes a class return the same single instance every time it is created, giving the program one shared object.

Key points

  1. _instance is a class attribute that stores the one shared object.
  2. __new__ is the method Python calls to create an object; it creates the object only when _instance is still None.
  3. cls._instance.theme = "dark" sets up the shared object once.
  4. first is second is True: both names point to the very same object.

When should you use it?

  • Application-wide configuration that every module reads.
  • One shared resource such as a cache, logger or connection pool.
  • Learning how __new__ controls object creation.

When not to use it

  • Most Python code: a module-level object (modules are created once) is simpler and does the same job.
  • Code you want to test easily: hidden global state makes tests depend on each other; pass the object in instead.

Example code

Run code →
main.py
class AppConfig:
    # Singleton: every caller receives one shared configuration object.
    _instance = None

    def __new__(cls):
        # Create the shared instance only on the first call.
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.theme = "dark"
        return cls._instance


first = AppConfig()
second = AppConfig()
print(first is second)
Get a Run button for this example

Result of running the code

True

Code explanation

__new__ is the method Python calls to create a new object, before __init__. The first time AppConfig() is called, _instance is None, so a real object is created, given its theme and stored on the class. Every later call skips that block and returns the stored object, which is why first is second prints True.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Common mistakes

Setting up state in __init__

__init__ runs on every call, so it resets the shared object each time.

Problem
def __init__(self):
    self.theme = "dark"  # runs again for every AppConfig()
Fix
if cls._instance is None:
    cls._instance = super().__new__(cls)
    cls._instance.theme = "dark"

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges