Python Metaclasses
In Python, classes are objects. Just as an object is an instance of a class, a class is an instance of a metaclass. The default metaclass in Python is type.
What is a Metaclass?
A metaclass is the class of a class. It controls the creation and behavior of classes.
- Object: Instance of a Class.
- Class: Instance of a Metaclass.
The type Metaclass
type is the built-in metaclass that Python uses to create all classes by default.
class MyClass:
pass
obj = MyClass()
print(type(obj)) # Output: <class '__main__.MyClass'>
print(type(MyClass)) # Output: <class 'type'>
Creating a Custom Metaclass
To create a custom metaclass, you must inherit from type. You typically override __new__ or __init__.
__new__(cls, name, bases, dct): Called to create the class.__init__(cls, name, bases, dct): Called to initialize the class.
class MyMeta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class: {name}")
x = super().__new__(cls, name, bases, dct)
x.custom_attribute = "Added by Metaclass"
return x
class MyClass(metaclass=MyMeta):
pass
# Output: Creating class: MyClass
print(MyClass.custom_attribute) # Output: Added by Metaclass
Example: Singleton Pattern
You can use a metaclass to implement the Singleton pattern, ensuring a class only has one instance.
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 Singleton(metaclass=SingletonMeta):
pass