Home Projects Blog

Upgrading Python without everything breaking

I put off fixing this issue for ~2 years because I (was lazy and) thought it would take hours to fix, turns out it was simple. This post is more for future me to remember what I did to upgrade Python and the fix in the event I will run into the problem again inevitably. It may help you, it most likely won't though.

I installed Python 3.7 and wanted to alias python3 to run Python version 3.7 instead of 3.5. Now I could just set an alias by adding alias python3=python3.7 to my .bashrc file but that change will only be local to my terminal and the user on the machine. With a bit of research I stumbled upon this article here.

The solution was to run sudo update-alternatives --config python3 and set the priority for version 3.7 to be number 1. This obviously didn't work as I am writing a post about it so what went wrong?

Running gnome-terminal comes up with the following error:

Traceback (most recent call last):
File "/usr/bin/gnome-terminal", line 9, in <module>
  from gi.repository import GLib, Gio
File "/usr/lib/python3/dist-packages/gi/__init__.py", line 42, in <module>
  from . import _gi
ImportError: cannot import name '_gi' from 'gi' (/usr/lib/python3/dist-packages/gi/__init__.py)

Given this error message, it probably means that I don't have gi installed. Poking around the directory shows that there are two files dependent on using Python 3.5, _gi.cpython-35m-x86_64-linux-gnu.so and _gi_cairo.cpython-35m-x86_64-linux-gnu.so. These two files are binaries and based on the information here, you can copy the files and rename it to the 3.7 version.
In my opinion, it's more elegant and cleaner to use a symlink for this as this means I can remember what I did and I don't have to deal with any cluttered files. You can create symlinks using the following command:

sudo ln -s /usr/lib/python3/dist-packages/gi/_gi_cairo.cpython-{35m,37m}-x86_64-linux-gnu.so
sudo ln -s /usr/lib/python3/dist-packages/gi/_gi.cpython-{35m,37m}-x86_64-linux-gnu.so

And with that everything is working again!

TL;DR

Install Python3.X.
Run sudo update-alternatives --config python3 and update it to your preferred version.
Run sudo ln -s /usr/lib/python3/dist-packages/gi/_gi_cairo.cpython-{3Ym,3Xm}-x86_64-linux-gnu.so
and sudo ln -s /usr/lib/python3/dist-packages/gi/_gi.cpython-{3Ym,3Xm}-x86_64-linux-gnu.so
replacing Y with the old Python3 version in use.