Short Introduction to Python Meta Classes

Recently i had an opportunity to work on re-writing the report generation code at Doselect. The code design must be such that which was modular and easy to implement in projects where generating different type of reports was important.

So to work on this task i had to learn about Python Meta classes, which by the way was my first time writing Meta class.

Lets get to the topic and discover a bit about Meta Class.

As weird it may seem, Classes in Python are fundamentally objects and they are of type, well, type. Classes are technically instance of meta class and by default python has type as a default meta class to all classes.

I can show this with a small code example.

class A:  
 pass
type(A)  
<class 'type'>

As you can see class A is a object of type “type” and “type” is a default to all the classes in python.

Now we come to the question of what exactly is the Metaclass?

Metaclasses are defined like any other Python class but there instances are normal python classes and they are classes that inherit from “type”. Meta class are called automatically called when the class statement ends.

Meta class are useful when you want to dynamically alter the behaviour of class during run-time.

Meta class can be implemented by using the class keyword and overriding the special __new__ method.

class ExampleMeta(type):  
    def __new__(cls, clsname, superclasses, attributedict):  
        print("clsname: ", clsname)  
        print("superclasses: ", superclasses)  
        print("attributedict: ", attributedict)  
        return type.__new__(cls, clsname, superclasses, attributedict)

Now when i define a class A and it called the associated metaclass automatically when i end my class statement.

class A(Superclass, metaclass=ExampleMeta):  
     pass

The output is:

clsname:  A  
superclasses:  (<class '__main__.Superclass'>,)  
attributedict:  {'__module__': '__main__', '__qualname__': 'A'}

We can see ExampleMeta.new has been called and not type.new.

This is just a short blog about Metaclass. To learn more about it. Here is a link.