Python Metaclasses

Python is an object-oriented language that simplifies working with classes. A class in Python defines specific behaviors for its instances, which are objects in Python. These class instances are created using the class as a blueprint. Similarly, a metaclass in Python describes behaviors for its instances, which are classes. A metaclass serves as the blueprint for the class itself, similar to how a class serves as the blueprint for instances of that class. The default metaclass is "type," and all metaclasses must inherit from the "type" metaclass.


Introduction to Python Metaclasses

Class-Factory

A metaclass serves primarily as a class factory. When you instantiate an object by invoking the class, Python generates a new class by utilizing the metaclass. By complementing the standard init and new methods, metaclasses offer the capability to incorporate additional functionalities during class creation, such as registering the freshly created class within a registry or substituting the class with an entirely different entity.

There are numerous use cases for metaclasses . Here are few:

  1. Automatic property creation
  2. Automatically adding new methods
  3. Registering classes at creation time
  4. Logging and profiling
  5. Interface checking

Metaclass's __new__() and __init__()

  1. __new__(): It's a method which is called before __init__(). It creates the object and return it. We can overide this method to control how the objects are created.

  2. __init__(): This method just initialize the created object passed as parameter.

Metaclasses can be defined in one of the two ways shown below.

class MyMeta1(type): def __new__(cls, name, bases, dict): pass
class MyMeta2(type): def __init__(self, name, bases, dict): pass

To exercise control over the construction and setup of classes within the metaclass, you can implement the metaclass's new method and/or init constructor. In practice, many metaclasses tend to override only one of these methods. Similar to a regular class, a metaclass possesses a new method responsible for generating the class instance and an init method that personalizes the instance. Additionally, if you intend to return an entity other than a freshly established class of the specific type, you must utilize new.

When to use Metaclasses?

In practical scenarios, the necessity for utilizing metaclasses is relatively infrequent. Typically, metaclasses come into play when there's a requirement for dynamic behavior that transcends the object level and is instead defined at the class level.

A Simple metaclass

We can use type directly to make a class, without any class statement. It can be called in following ways:

  1. When called with only one argument, it returns the type.
  2. When called with three parameters, it creates a class. Following arguments are passed to it:
    1. Class name
    2. Tuple having base classes inherited by class
    3. Class Dictionary

It's because the function type is in fact a metaclass. type is the metaclass Python uses to create all classes behind the scenes.

>>> SomeClass = type('SomeClass',(),{}) >>> SomeClass <class '__main__.SomeClass'>

The class statement isn't just syntactic sugar, it does some extra things, like setting an adequate __qualname__ and __doc__ properties or calling __prepare__ .

The __prepare__ method

The prepare method is invoked prior to executing the class body, and its role is to yield a dictionary-like object which serves as the local namespace for the entirety of the code within the class body. When the metaclass has a prepare attribute, it's invoked with the arguments namespace = metaclass.prepare(name, bases, **kwds). Conversely, in cases where the metaclass lacks a prepare attribute, the class namespace gets initialized as an empty ordered mapping. This feature was introduced in Python 3.0.


Python metaclasses by example

Creating custom Metaclass

The primary objective of a metaclass is to automatically modify a class during its creation. This practice is typically applied to APIs, where the goal is to generate classes that align with the present context. To craft a custom metaclass, it should inherit from the type metaclass and commonly override:

custom metaclass:
>>> class MyMeta(type): ... pass

And then we can use it

>>> class DoIT(metaclass=MyMeta): ... pass >>> type(DoIT) <class '__main__.MyMeta'>

Conclusion

Python metaclasses are a powerful feature that allows you to control the creation and behavior of classes. They provide a way to customize class creation and can be used to implement dynamic behaviors that operate at the class level, offering advanced capabilities beyond traditional class inheritance.