capypad
0 day streak
python / expert
Snippet

Metaclasses for Singleton Enforcement

Metaclasses are the 'classes of classes'. By overriding the __call__ method of a metaclass, you can control the instantiation process of its classes. In this example, the metaclass ensures that only one instance of the Database class ever exists by storing and reusing it in a private dictionary.

snippet.py
python
1
2
3
4
5
6
7
8
9
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
 
class Database(metaclass=Singleton):
pass
Breakdown
1
class Singleton(type):
Inheriting from 'type' defines this class as a metaclass.
2
def __call__(cls, *args, **kwargs):
Intercepts the class constructor call to manage object creation.
3
metaclass=Singleton
Instructs Python to use the Singleton metaclass for the Database class definition.