Abstract: In this article, we’ll take a closer look at Python metaclasses, their properties, and how and when to use them in Python.

Python metaclasses set the behavior and rules of classes. Metaclasses help modify instances of classes, and are quite complex, making them one of the advanced features of Python programming. In this article, you’ll dive into Python metaclasses, their properties, and how and when to use them in Python. This article introduces the following concepts:

  • What is a Python metaclass?
  • Classes and objects in Python
  • Dynamic classes in Python
  • How do Python metaclasses work?
  1. Type class
  2. Custom metaclasses in Python
  • Decorator vs metaclass

What is a Python metaclass?

The Python metaclass is one of the advanced features associated with Python’s object-oriented programming concepts. It determines the behavior of the class and further assists in its modification.

Every class created in Python has a basic Metaclass. Therefore, when creating classes, you will use metaclasses indirectly. It happens implicitly, and you don’t have to specify anything.

The metaclass associated with metaprogramming determines the ability of a program to operate on itself. Learning about metaclasses may seem complicated, but let’s start with some class and object concepts to make it easier to understand.

Classes and objects in Python

A class is a blueprint, a logical entity with objects. A simple class does not allocate any memory when it is declared; it happens when an instance of the class is created.

This class can be accessed by creating objects. This class is used only as a template. Properties of an object essentially mean that we can interact with it at run time, passing parameters like variables, storing, modifying, and interacting with it.

You can use the __class__ attribute to check the class of an object. Let’s look at a simple example:

Output: <class ‘__main__.Demo’>

Python deals extensively with the concept of classes and objects and allows easy, smooth application development. But what makes Python different from languages like Java and C? Everything in Python**** can be defined as objects with properties and methods. The keynote was that a class in Python is just another object in a larger class.

Classes define rules for objects. Similarly, metaclasses are responsible for assigning behavior to classes. We already know that a class is an object, just as every object has an instance, a class is an instance of a metaclass.

But there are also languages like Ruby and Objective-C that support metaclasses. So, what makes Python Metaclass better, and why learn it? The answer is dynamic classes in Python. Let’s take a closer look.

Dynamic classes in Python

Python is a dynamic programming language and allows classes to be created at run time. Unlike other languages such as C ++, which only allow classes to be created at compile time. Python is superior to other statically typed languages in terms of flexibility.

The difference between dynamically and statically typed languages is not that great, but in Python it becomes more useful by providing metaprogramming.

But what if I told you that there’s another key feature that sets Python apart from other programming languages?

Whereas languages such as Java or C ++ have data types such as float, char, int, etc., Python treats each variable as an object. Each object belongs to a class, such as int or STR. You can simply check the class of any variable using a built-in function called type**** ().

Output:

Type associated is: <class ‘int’>

Type associated is: <class ‘str’>

Now you know that everything in Python has a type associated with it. In the next topic, we’ll try to understand how metaclasses actually work.

How do Python metaclasses work?

The default Metaclass type is called every time aclass is created. Metaclasses contain information such as the name, the base class set, and the attributes associated with the class. Therefore, when a class is instantiated, the class with these parameters is called. Metaclasses can be created in two ways:

1. The class type

2. Customize metaclasses

Let’s continue typing class and how to create a class.

Type class

Python has a built-in metaclass called Type. Unlike Java or C, there are primary data types. Every variable or object in Python has a class associated with it. Python uses the Type class behind the scenes to create all classes. In the last topic, we saw how to use **type**** () to check the class of an object. ** Let’s take an example of how to define a new type by creating a simple class.

Output: <class ‘__main__.Edureka’>

Output: <class ‘type’>

In the above code, we have a class named Edureka and an associated object. We created a new type named Edureka by simply creating a class named itself after the type. In the second code, when we check the type of the Edureka class, the result is “type.”

Therefore, unless otherwise defined, metaclasses use type classes to create all other classes. We can access the Type class in two ways:

When we pass parameters through the type class, it uses the following syntax.

  • The name is a string with the class name
  • The base is a tuple that helps create subclasses
  • The property is a dictionary and assigns key-value pairs

Because classes in Python behave like objects, you can change their behavior in the same way. We can add or remove methods within a class, similar to how we treat objects.

You now know that Metaclass creates all the other classes in Python and defines their behavior using the type class. But, you must be wondering, is there another way we can create metaclasses? So let’s look at how to create a custom metaclass.

Custom metaclasses in Python

Now we know and understand how type classes work. Now it’s time to learn how to create a custom metaclass. We can modify the work of a class by performing actions or code injection. To do this, we can pass Metaclass as a keyword when creating the class definition. Alternatively, we can do this by simply inheriting the class instantiated with the Metaclass keyword.

When creating a new class, Python looks for the **__metaclass__** keyword. Just in case it doesn’t exist. It follows a type class hierarchy.

After Python executes all dictionaries in the namespace, it calls the type object, which creates the object of the class. There are two ways to create a custom metaclass.

Let me elaborate on these two methods:

1.__new __**** () : used when the user wants to define a tuple dictionary before the class is created. It returns an instance of a class and makes it easy to overwrite/manage object streams.

2. __init __**** () : Call the object after it has been created and initialized.

** What is __call__** in Python?

In formal Python documentation, the **__call__** method can be used to define a custom metaclass. Similarly, we can override other methods such as __prepare__ when calling classes to define custom behavior.

Just like how classes act like templates for creating objects, metaclasses act like templates for classes. Therefore, metaclasses are also called class factories.

See the next example:

Output: 200

Metaclasses allow you to customize classes. There are a variety of other effective and much simpler ways to achieve the same output through these methods. One such example is the use of decorators.

Decorator vs metaclass

Decorators are a popular Python feature that allows you to add more functionality to your code. Decorators are callable objects that help modify existing classes and even functions. During compilation, one part of the code calls and modifies the other. This process is also known as metaprogramming.

Output: 200

The Decorator in Python is a very useful and powerful tool to help you change the behavior of a function without actually changing any code. This is handy when you want to modify part of the program while debugging rather than rewriting functions or changing the entire program. Instead, you just write a one-line decorator and it takes care of the rest.

This article is adapted from the huawei Cloud community how to Create Your First Python metaclass? , original author: Yuchuan.

Click to follow, the first time to learn about Huawei cloud fresh technology ~