How to create an instance of a Metaclass that run on both Python2 and Python3?
Last Updated :
01 Oct, 2020
Metaclasses are classes that generate other classes. It is an efficient tool for class verification, to prevent sub class from inheriting certain class function, and dynamic generation of classes. Here we will discuss how to create an instance of a Metaclass that runs on both Python 2 and Python 3. Before delving into it, let's go through the code design for each Python version.
Python 3
In Python 3, an instance of a metaclass is created while declaring a class, by providing the Metaclass to the metaclass keyword argument. Let's look into the preferred way of doing this in Python 3.
Python3
class MetaCls(type):
def __new__(cls, name, bases, attrs):
return super(MetaCls, cls).__new__(cls, name, bases, attrs)
class C(object, metaclass=MetaCls):
pass
print('Type of class C:',type(C))
OutputType of class C: <class '__main__.MetaCls'>
Here, we have created a class called C by providing the MetaCls class to the metaclass keyword argument. You can see the type of class C as MetaCls.
Note: MetaCls is a metaclass that directly inherited from type.
Python 2
Now, let look into, how to create an instance of a metaclass in Python 2. In Python 3, we have seen that the metaclass is mentioned in the keyword argument during class declaration; whereas in Python 2, a metaclass is assigned in the class body by using a __metaclass__ attribute. Let's see the code below:
Python
class MetaCls(type):
def __new__(cls, name, bases, attrs):
return super(MetaCls, cls).__new__(cls, name, bases, attrs)
class C(object):
__metaclass__ = MetaCls
print(type(C))
Output<class '__main__.MetaCls'>
Metaclass code that runs on both Python 2 and Python 3
Now it's clear how the syntax differs in Python 2 and Python 3. This difference in syntax may create trouble if you are trying to migrate your Python 2 code to Python 3. Since Python 3 is backward incompatible, the Python 3 syntax doesn't execute on Python 2 and vice versa.
Here comes the importance of a tool called six. It provides two ways to declare a metaclass that ensures cross-compatibility.
- By creating a stand-in class
- As a decorator
In the first method, we will create a stand-in class and use it as a direct subclass. Let's look into the below code.
Python3
import six
class MetaCls(type):
def __new__(cls, name, bases, attrs):
return super(MetaCls, cls).__new__(cls, name, bases, attrs)
class C(six.with_metaclass(MetaCls)):
pass
print(type(C))
Output<class '__main__.Meta'>
Now, let's see how to create an instance of metaclass by using a decorator.
Python3
import six
class MetaCls(type):
def __new__(cls, name, bases, attrs):
return super(MetaCls, cls).__new__(cls, name, bases, attrs)
@six.add_metaclass(MetaCls)
class C(object):
pass
print(type(C))
Output<class '__main__.MetaCls'>
Similar Reads
How to Add Attributes in Python Metaclass? This article explains what a metaclass is in the Python programming language and how to add attributes to a Python metaclass. First, let's understand what a metaclass is. This is a reasonably advanced Python topic and the following prerequisites are expected You have a good grasp of Python OOP Conce
4 min read
How To Fix "Typeerror: Cannot Create A Consistent Method Resolution Order (Mro)" In Python When working with Python, it is usual to encounter mistakes. One such issue, "TypeError: Cannot create a consistent method resolution order (MRO)," might be very aggravating. This issue usually occurs when there is a dispute in the inheritance structure of classes. In this article, we will explore t
3 min read
Pass Arguments to the Metaclass from the Class in Python Metaclasses in Python provide a powerful way to control the creation and behavior of classes. They act as the "class of a class" and allow you to customize class creation and behavior at a higher level. One interesting aspect of metaclasses is the ability to pass arguments from a class to its metacl
3 min read
Automate the Conversion from Python2 to Python3 We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3. Installation This module does not come built-in with Python. To install this type the below command in the
1 min read
Important differences between Python 2.x and Python 3.x with examples In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling
5 min read
What is a clean and Pythonic way to have multiple constructors in Python? Python does not support explicit multiple constructors, yet there are some ways to achieve multiple constructors. We use Python's inbuilt __init__ method to define the constructor of a class. It tells what will the constructor do if the class object is created. If multiple __init__ methods are writt
7 min read
Python VLC Instance - Setting Meta Data of Application In this article we will see how we can set the meta information of the application from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as
2 min read
Call a Class Method From another Class in Python In object-oriented programming, classes play a pivotal role in organizing and structuring code. Python, being an object-oriented language, allows the creation of classes and their methods to facilitate code modularity and reusability. One common scenario in programming is the need to call a method f
3 min read
How to Check the Type of an Object in Python In this article, we will explore the essential skill of determining the type of an object in Python. Before engaging in any operations on an object within the Python programming language, it is imperative to possess the knowledge of how to check its type. This fundamental task is encountered regular
4 min read
OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super) We have discussed following topics on Object Oriented Programming in Python Object Oriented Programming in Python | set-1 Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing) In this article, Inheritance is introduced. One of the major advantages of Object Oriented Program
4 min read