Product Development
Embracing the Future: Making the Leap from Python 2 to Python 3
Python 2 to Python 3 Migration:
Introduction
In the computer field there daily technology comes and will regularly update. We need to use the application with the latest technology and libraries for better understanding, efficiency and reduce cost of time. There is a possibility that the application is developed in particular technology and it is very old. So, for better understanding we need to upgrade it. So, here we are discussing how to migrate python2 to python3.Why we need to migrate Python 2 to Python 3?
1. Accuracy:- Python 2
E.g. if you divide 5 by 2 in Python2, it gives the result as 2.
- Python 3
E.g. if you divide 5 by 2 in Python3, it gives the result as 2.5.
2.Storage of strings: In python 2, by default strings are stored as ASCII. In python3, by default strings are stored as UNICODE. 3.Syntax: Python 3 has easier syntax compared to Python 2. 4.Libraries: A lot of libraries in python 2 are not forward compatible and packages are not well managed whereas in Python 3 Packages are well managed. 5.Use: Python 2 is generally used in DevOps. Python 3 is used in a lot of fields like Data Science, Machine learning, Deep learning, Software engineering. Note: You must have knowledge of python 2 and python 3 supported libraries and syntax.Read: Web Scraping with Python
Now we can convert the python 2.x code to python 3.x using the 2to3 Module. To Install 2to3 module use below command.
pip install 2to3
Here is a simple example to demonstrate the conversion of the test.py file from Python 2 to Python 3 . test.py(in Python 2) def demo(name): print “Name is, {0}!”.format(name) print “What is your name?” name = raw_input() demo(name) By using the 2to3 library, we can convert the python 2 code into python 3 code. To convert it use the below command, 2to3 test.py To apply diff or to modify the file need to use below command, 2to3 -w test.py After converting the code in python 3 it looks like, def demo(name): print (“Name is, {0}!”.format(name)) print (“What is your name?”) name = input() demo(name)To make your project in Python 3.x. the basics steps are.
- You must have good test coverage. coverage
- You need to learn the difference between python 2 and python 3.
- To update your code use Futurize and Modernize
- Don’t regress on python 3 code support use pylint
- To find the which dependencies are blocking in python 3, use caniusepython3
- You can integrate once your dependencies are not blocked . To test against the multiple version of python use tox
- To make sure your type usage works in both python 2 and python 3 consider using optimal static type checking.