Course contentsShow
← Python
Lesson 616 of 1,06010. Advanced Language FeaturesFree lesson

Implementing Singleton Patterns using Metaclasses

Control the instantiation process of a class to ensure only a single instance exists throughout the entire application lifecycle.

In this lesson, you will learn how to leverage Python metaclasses to enforce the Singleton pattern, ensuring that a class has only one instance throughout your application's lifecycle.

Understanding the Singleton Challenge

The Singleton pattern is often implemented using decorators or simple class variables. However, using a metaclass is the most "Pythonic" and robust way to achieve this because it intercepts the creation process at the root: the class construction level. By overriding the __call__ method of a metaclass, we can dictate exactly what happens when a user attempts to instantiate a class.

Implementing the Singleton Metaclass

A metaclass acts as a template for your classes. When you call a class (e.g., MyClass()), Python invokes the __call__ method of its metaclass. We can use this to check if an instance already exists in a dictionary and return it if it does.

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        # Check if the instance exists; if not, create it once
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]

# Usage
class DatabaseConnection(metaclass=SingletonMeta):
    def __init__(self):
        print("Initializing database connection...")

# Even if we call this twice, the __init__ logic runs only once
db1 = DatabaseConnection()
db2 = DatabaseConnection()

print(db1 is db2)  # True

Why use this approach?

By placing this logic in a metaclass, you abstract the "Singleton-ness" away from the business logic of your classes. You don't need to add if statements or static variables inside your domain classes. Instead, any class you define with metaclass=SingletonMeta automatically inherits the restriction that it can only ever be instantiated once. This separation of concerns makes your codebase cleaner, easier to maintain, and highly predictable when dealing with global state like configuration managers or resource pools.

Key Takeaway: By overriding the __call__ method in a custom metaclass, you intercept the object creation process, allowing you to return the same persistent instance every time a class is invoked.