How to write a metaclass that supports both python2 and python3

The syntax for using metaclass is different between python2.x and python3.x. On the other hand, you may want to support both versions in one file. How to write in such a case.


There are the following metaclass HasVersionMeta. A metaclass that simply has a string like a version number.

class HasVersionMeta(type):
    def __new__(cls, name, bases, attrs):
        attrs["version"] = "0.0.1"
        return super(HasVersionMeta, cls).__new__(cls, name, bases, attrs)

I want to define a class that uses this.

For python3

In the case of python3, add the metaclass option to the argument passed when inheriting.

class A(object, metaclass=HasVersionMeta):

For python2

For python2, assign it to a hook with a special name metaclass

class A(object):
    __metaclass__ = HasVersionMeta

When supporting both

The class used as a metaclass is also a callable object. Considering that the parent class type () is used when dynamically generating a class, it should have the same function. So you can write as follows.

HasVersion = HasVersionMeta("A", (object, ), {"__doc__": HasVersionMeta.__doc__})

class A(HasVersion):


# 0.0.1

Recommended Posts

How to write a metaclass that supports both python2 and python3
[Python] How to write a docstring that conforms to PEP8
How to write a list / dictionary type of Python3
How to manage a README for both github and PyPI
[Python] How to play with class variables with decorator and metaclass
How to write a test for processing that uses BigQuery
How to start a simple WEB server that can execute cgi of php and python
[Python] How to add rows and columns to a table (pandas DataFrame)
How to make a surveillance camera (Security Camera) with Opencv and Python
Difference in how to write if statement between ruby ​​and python
Try to write a program that abuses the program and sends 100 emails
A quick guide to PyFlink that combines Apache Flink and Python
How to package and distribute Python scripts
Qiita (1) How to write a code name
[Python] How to convert a 2D list to a 1D list
How to write Python document comments (Docstrings)
How to get a stacktrace in python
python: How to use locals () and globals ()
[Python] How to calculate MAE and RMSE
How to use Python zip and enumerate
Compress python data and write to sqlite
How to use is and == in Python
How to write Ruby to_s in Python
How to run a Maya Python script
How to write pydoc and multi-line comments
How to call a POST request that supports Japanese (Shift-JIS) with requests
How to write the correct shebang in Perl, Python and Ruby scripts
A memorandum of how to write pandas that I tend to forget personally
How to put a half-width space before letters and numbers in Python.
How to use hmmlearn, a Python library that realizes hidden Markov models
[Introduction to Python] How to write a character string with the format function
How to stop a program in python until a specific date and time
How to read a CSV file with Python 2/3
How to create a Python virtual environment (venv)
How to open a web browser from python
How to clear tuples in a list (Python)
How to generate permutations in Python and C ++
How to embed a variable in a python string
How to create a JSON file in Python
[Python] How to read data from CIFAR-10 and CIFAR-100
How to generate a Python object from JSON
How to convert SVG to PDF and PNG [Python]
Output python log to both console and file
Why does Python have to write a colon?
How to write a ShellScript Bash for statement
How to notify a Discord channel in Python
Python: Create a class that supports unpacked assignment
[Python] How to use hash function and tuple.
[Python] How to draw a histogram in Matplotlib
How to write async and await in Vue.js
How to write a named tuple document in 2020
[Go] How to write or call a function
I want to write to a file with Python
How to write a ShellScript bash case statement
How to plot autocorrelation and partial autocorrelation in python
How to write environment variables that you don't want to put on [GitHub] Python
[Python] Concatenate a List containing numbers and write it to an output file.
How to install a Python library that can be used by pharmaceutical companies
I want to exe and distribute a program that resizes images Python3 + pyinstaller
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
How to install Python