Python 3 Deep Dive Part 4 Oop High Quality -
A metaclass is to a class what a class is to an instance. The default metaclass is type.
def my_meta(name, bases, dct): dct['version'] = 1.0 return type(name, bases, dct)class MyClass(metaclass=my_meta): pass
print(MyClass.version) # 1.0
Practical use: Singleton metaclass:
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 Database(metaclass=SingletonMeta): pass
When to use metaclasses (rarely!):
High-quality rule: If you’re unsure, don’t use metaclasses. They make code magical and hard to debug. Prefer class decorators.
class ValidatePlugin(Plugin): name = "validator" python 3 deep dive part 4 oop high quality
def process(self, data):
if "id" not in data:
raise ValueError("Missing ID")
return data
This design is extensible, testable, and respects LSP, OCP (Open/Closed), and DIP (Dependency Inversion).
When you use multiple inheritance, Python uses the C3 Linearization algorithm to determine which method is called. You can inspect this via __mro__. A metaclass is to a class what a class is to an instance