Python › Metaclasses & Class Customization
How can a metaclass be used to implement the Singleton design pattern more robustly than overriding __new__ alone?
AdvancedAnswer
A Singleton metaclass overrides __call__(cls, *args, **kwargs) (the method invoked when you 'call' the class to create an instance) to check a per-class instance cache and return the existing instance instead of creating a new one. This centralizes the singleton logic in one reusable metaclass applicable to any class, rather than duplicating __new__ overrides in every singleton class.
class SingletonMeta(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 Config(metaclass=SingletonMeta):
pass
print(Config() is Config()) # TrueReal-world example An application-wide logging configuration class uses a SingletonMeta metaclass so every part of the codebase that instantiates Config() transparently receives the same shared instance.