When to use metaclasses in Python: 5 interesting use cases
Metaclasses are mentioned among the most advances features of Python. Knowing how to write one is perceived like having a Python black belt. But are they useful at all outside job interviews or conference talks? Let's find out! This article will show you 5 practical applications of metaclasses. The legend says there was a Python developer that actually used metaclasses in their code What metaclasses are - quick recap Assuming you know the difference between classes and objects, metaclasses should not be that difficult - they are classes for classes (hence "meta" in their name). Simply saying - while classes are blueprints for objects, metaclasses are blueprints for classes. Class acts as a blueprint when we create an instance of it whereas metaclass acts as a blueprint only when a class is defined. The simplest implementation of a metaclass that does nothing looks as follows: # inherit from type class MyMeta(type): # __new__ is a classmethod, even without @classmethod decorator def __new__(cls, name, bases, namespace): # cls - MyMeta # name - name of the class being defined (MyClass in this example) # bases - base classes for constructed class, empty tuple in this case # namespace - dict with methods and fields defined in class # in this case - {'x': 3}
breadcrumbs collector.tech