Python metaclass – Complete Reference

Filed Under: Python

The term metaprogramming refers to the potential for a program to have knowledge of or manipulate itself. Python supports a form of metaprogramming for classes called metaclasses

Metaclasses are an esoteric OOP concept. You use them whether you are aware of it or not. Most Python programmers rarely, if ever, have to think about metaclasses.

Let’s take a look at metaclasses in detail. By the end of the article, you’ll have a complete understanding of:

  • What is a metaclass in Python?
  • What are some of the built-in metaclasses defined within Python?
  • How metaclasses work?
  • How to create metaclasses in Python?

To understand metaclasses, you need to have a good understanding of inheritance and multiple inheritance in Python.

So if you do not know what they’re, I’d recommended you to take a look at the tutorials linked above. When you’re ready, we can proceed further on this tutorial.

What is a Metaclass in Python?

Python metaclass is a class that instantiates another class. In Python, a class is an object of another class. This other class is called a metaclass.

Metaclasses in Python define the behavior of class objects. Let’s look at some examples to understand the metaclass concept clearly.

Understanding the built-in Metaclass in Python

type is a built-in metaclass in Python. Let’s start with the following example:

class SampleClass():
   pass
obj = SampleClass()
print(type(obj))

In the above code we have created a class named SampleClass, and creating an object of it. Then type of object says:

class '__main__.SampleClass'

That means obj is an object of SampleClass. Now if we try to see the type of SampleClass itself as following:

print(type(SampleClass))

Then the output is:

class 'type'

That means SampleClass is an object of class type. To be more specific SampleClass is an instance of class type. So type is a metaclass. Every class of python belongs to the built-in metaclass type.

How metaclasses work?

Whenever we create any class then the default metaclass gets called. This metaclass gets called with three information – name of the class, set of base classes of the class and the attributes of the class.

As type is the builtin metaclass, whenever we create a class type gets called with these three argument.

We are saying that every class in python is also a object of type, which means we can create any class in a single line just like we create object of any class. This way of creating a class is called “creating class on the fly”.

Create python Class using metaclass

So using the metaclass type, you can create your class in a single line by calling as following:

Student = type('Student', (), {})

This will create a class named Student at run time of the code. The above line is equivalent to the following code:

class Student:
   pass

If inherits some other class say for example Department then we write as following,

class Student(Department):
   pass

Inherited classes should be provided in the second argument when creating class on the fly,

Student = type('Student', (Department,), {})

If Student class contains some attributes and functions then they should be provided in the 3rd argument as key value pair. See following the examples:

class Student:
  
   def __init__(self, name, roll):
       self.name = name
       self.roll = roll
       self.marks = 0.0

Those attributes and functions can be added as following:

def init(self, name, roll):
   self.name = name
   self.roll = roll
   self.marks = 0.0


Student = type('Student', (), {'__init__' : init})

Notice that we have defined the function before we use it. One more thing I want you to understand is that the first argument is class name. So if you write as following:

Student = type('StudentClass', (), {'__init__' : init})
obj = Student("Zinia", "59")
print(obj.__class__)

Then the output will be,

class '__main__.StudentClass'

So, it’s better to keep the same name for class and variable to keep consistency.

Set the metaclass

You can set your class’s metaclass explicitly. Whenever python gets the keyword class then it searches for the metaclass. If not found then the default metaclass type is used to create the object of the class. You can set metaclass of your class using the __metaclass__ attribute as following:

class SomeClass:
   __metaclass__ = type
   # other methods...

print(SomeClass.__metaclass__)

It will produce output as;

class 'type'

Creating Metaclass in Python

Finally, you can also create your own metaclass to define the behaviour of any class that are created using your class.

To do that your class must inherit the default metaclass type as this is the main metaclass. See the following example:

python metaclass

It will output:
metaclass in python

Conclusion

Metaclass in Python is a very complicated topic. Here we have given the basic idea of a metaclass. Hope now, you do understand the basic concept of a metaclass. To understand the functionalities of metaclass you have to go very deep. However, you should be aware of how Python classes work and what is the role of metaclass in python.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages