Upgrade today!!
Let’s talk about Python 2to3 , an automated code translator. This is a great tool to convert your python2 project to python3.


Why you should move to python 3.x?

Checkout https://pythonclock.org/ (If that link is no more available, I have added the screenshot below)

Python 2 reached end of life (EOL) on January 1st, 2020

And python3 supports typing (:heart_eyes:) and a lot more (will cover it some other time).

So, let’s take a look at how to use 2to3 to actually upgrade the code itself.


Let’s start with a simple example

2to3 example.py

Nothing fancy, It will just print the code changes to be done in example.py to make it compatible with python3.x We will add -W to make it actually edit the file.

More useful example is to upgrade the whole project, we will see it in sometime.

But before going ahead, please make sure that you are using some kind of version control for your project (e.g> git). So that we don’t need to worry about old code. Just rely on version control system.

First, create a new branch for making the changes

git checkout -b pg/code_upgrade_python3

Now, you don’t need to worry about any code changes since all the changes we make will reside in this branch only.

Execute following to get a glimpse

2to3 --output-dir=./python3_version -W -n ./

This will consider all .py files in current directory and upgrade it for python3.x then put all the changes into python3_version directory. Take a look at files in python3_version. Once satisfied with the changes remove that directory rm -rf ./python3_version

Now, replace the files with new code

2to3 --output-dir=./ -W -n ./

For upgrading requirements/dependencies, I would suggest you to create a new virtual environment first. I use virtual environment wrapper

mkvirtualenv --python=/usr/local/bin/python3.6 project_python3

Create a temp file file with all requirements without specifying the version

vim /tmp/req

After adding all requirements to temp file, execute following

pip3 install -r /tmp/req

Now, your new environment is ready for testing. Perform all possible tests on your upgraded codebase and then add few more test cases :laughing:

Execute following to update your requirements.txt with correct version numbers

pip freeze > path_to_requirements

Make sure to use version control for project and new virtual environment while upgrading the requirements.

Welcome to python3 world!

🏆