Design Pattern Implementer | Python

Singleton Pattern Implementation in Python

Learn to implement the Singleton Pattern in Python using a metaclass to control instance creation, ensuring a single instance per class. Globally accessible and avoids multiple instantiations.


Empty image or helper icon

Prompt

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class SingletonClass(metaclass=SingletonMeta):
    pass

singleton_1 = SingletonClass()
singleton_2 = SingletonClass()

print(singleton_1 == singleton_2)

Answer

Design Pattern: Singleton Pattern

Problem Analysis:

  • The provided code snippet demonstrates the implementation of the Singleton Pattern using a metaclass in Python.
  • The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it.

Code Template - Singleton Pattern Implementation:

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class SingletonClass(metaclass=SingletonMeta):
    pass

# Singleton instances
singleton_1 = SingletonClass()
singleton_2 = SingletonClass()

print(singleton_1 == singleton_2)  # Outputs: True (both variables point to the same instance)

Explanation:

  • The SingletonMeta metaclass is used to control the creation of instances of classes that use it.
  • Within the metaclass, a dictionary _instances is maintained to store instances of classes.
  • The __call__ method in the metaclass ensures that only one instance of a class is created and returned upon instantiation.
  • By setting the metaclass of the SingletonClass to SingletonMeta, we enforce the Singleton Pattern for SingletonClass.
  • When singleton_1 and singleton_2 are created, they both point to the same instance due to the nature of the Singleton Pattern.

Key Points:

  1. The Singleton Pattern restricts the instantiation of a class to a single instance.
  2. Using a metaclass like SingletonMeta allows for centralized control over instance creation.
  3. Access to the singleton instance is provided globally across the application.
  4. The pattern ensures that all calls to create an object return the same instance.

By following this code template and understanding the Singleton Pattern's implementation, you can enforce singleton behavior in your Python classes effectively.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

Learn to implement the Singleton Pattern in Python using a metaclass to control instance creation, ensuring a single instance per class. Globally accessible and avoids multiple instantiations.