Python Singleton Metaclass: Ensure One Instance
Python Metaprogramming: Exercise-3 with Solution
Singleton Metaclass:
Write a Python program to create a metaclass SingletonMeta that ensures a class only has one instance (singleton pattern).
Sample Solution:
Python Code :
# Define a metaclass SingletonMeta
class SingletonMeta(type):
# Dictionary to store instances of classes
_instances = {}
# Override the __call__ method of the metaclass
def __call__(cls, *args, **kwargs):
# Check if the class is not already instantiated
if cls not in cls._instances:
# If not, create a new instance and store it in _instances dictionary
cls._instances[cls] = super().__call__(*args, **kwargs)
# Return the existing instance if already instantiated
return cls._instances[cls]
# Create a class SingletonClass using SingletonMeta as its metaclass
class SingletonClass(metaclass=SingletonMeta):
pass
# Test the singleton class
# Create two instances of SingletonClass
instance1 = SingletonClass()
instance2 = SingletonClass()
# Check if both instances refer to the same object
print(instance1 is instance2) # True
Output:
True
Explanation:
- SingletonMeta Metaclass:
- It defines a metaclass named "SingletonMeta".
- It maintains a dictionary '_instances' to store instances of classes created using this metaclass.
- call Method:
- This method is called whenever an instance of a class with "SingletonMeta" as its metaclass is created.
- It checks if an instance of the class already exists in '_instances'.
- If not, it creates a new instance using super().__call__(*args, **kwargs) and stores it in '_instances'.
- It returns the existing instance if it's already instantiated.
- SingletonClass:
- It's a class that uses 'SingletonMeta' as its metaclass.
- As a result, instances of 'SingletonClass' will be singletons, meaning only one instance will exist throughout the program.
- Testing SingletonClass:
- Two instances ('instance1' and 'instance2') of "SingletonClass" are created.
- The 'is' operator checks if both instances refer to the same object.
- Since the Singleton pattern ensures that only one instance exists, 'instance1 is instance2' returns 'True'.
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Python Metaclass Tutorial: Validate Attributes as Integers.
Next: Python Attribute Logging Metaclass: Monitor Accesses.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics