How to Implement a Singleton Class in Python

This code demonstrates a classic Singleton pattern in Python by overriding __new__ to ensure only one instance of the class is created, even when instantiated multiple times.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 15 views 0 copies

Python code

18 lines
Python 3.9+
class Singleton:
    _instance = None

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

    def __init__(self):
        self.value = 0


if __name__ == "__main__":
    s1 = Singleton()
    s2 = Singleton()
    s1.value = 42
    print(s1 is s2)
    print(s2.value)

Output

stdout
True
42

How it works

The Singleton class overrides __new__ to control instance creation. A class attribute _instance stores the single instance, initially None. When creating an instance, if _instance is None, a new instance is created and assigned; otherwise, the existing instance is returned. This ensures s1 and s2 point to the same object, so setting value on s1 is reflected in s2. The __init__ method still runs on each instantiation, so in practice you might guard state initialization to avoid overwriting.

Common mistakes

  • Forgetting that `__init__` runs every time, which can reset instance state
  • Not using thread-safe locking in multi-threaded environments
  • Assuming class inheritance will catch the singleton behavior without overriding again

Variations

  1. Use a decorator to wrap the class and cache instances
  2. Use a metaclass to enforce singleton behavior across subclasses

Real-world use cases

  • Managing a single database connection pool across an application to avoid resource leaks.
  • Sharing a global configuration object that is loaded once and accessed everywhere.
  • Implementing a central logging service to ensure consistent log formatting and single file handle.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.