Python Design Patterns

Singleton Pattern in Python

Singleton is useful when exactly one coordinated object should manage shared state or a resource.

What is Singleton Pattern?

Singleton is useful when exactly one coordinated object should manage shared state or a resource.

Ensure a class has one shared instance and provide a global access point.

When should you use it?

  • Solve recurring object-design problems with proven structures.
  • Decouple responsibilities so code is easier to extend and test.
  • Use shared design vocabulary when discussing architecture with a team.

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)

Expected output

True

How it works

__new__ creates the object once and returns that same instance on later construction calls.

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 Python IDE →