'How can I update Google Colab's Python version?

The current default version of Python running on Google Colab is 3.7, but I need 3.9 for my notebooks to work.

How can I update Google Colab's Python version to 3.9 (or greater)?



Solution 1:[1]

In Google Colab you have a Debian-based Linux, and you can do whatever you can on a Debian Linux. Upgrading Python is as easy as upgrading on your own Linux system.

Detect Python version in Colab:

!python --version
#3.7.11

Now let's install and upgrade to Python 3.9:

#install python 3.9
!sudo apt-get update -y
!sudo apt-get install python3.9

#change alternatives
!sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1
!sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 2

#check python version
!python --version
#3.9.6

Note that all changes will be lost after restarting the kernel. Each runtime gives you a fresh google colab.

Also, note that you can see a list of installed Python versions and switch between them at any time with this command: (If nothing changed after installation, use this command to select python version manually)

!sudo update-alternatives --config python3
#after running, enter the row number of the python version you want. 

NOTE: As mentioned in the comments, the above commands just add a new python version to your google colab and update the default python. But your runtime packages such as sys are still running on the previous default python version. For your new installed python, you need to install everything from scratch.

Solution 2:[2]

To use another python version in google colab, you need to: 1- Installing Anaconda. 2- Adding (fake) google colab library. 3- Starting Jupyterlab. 4- Accessing it with ngrok.

# install Anaconda3
!wget -qO ac.sh https://repo.anaconda.com/archive/Anaconda3-2020.07-Linux-x86_64.sh 
!bash ./ac.sh -b

# a fake google.colab library
!ln -s /usr/local/lib/python3.6/dist-packages/google \
       /root/anaconda3/lib/python3.8/site-packages/google

# start jupyterlab, which now has Python3 = 3.8
!nohup /root/anaconda3/bin/jupyter-lab --ip=0.0.0.0&

# access through ngrok, click the link
!pip install pyngrok -q
from pyngrok import ngrok
print(ngrok.connect(8888))

you can also use:

# Install the python version
!apt-get install python3.9

# Select the version
!python3.9 setup.py

another way is to use a virtual environment with your desired python version:

virtualenv env --python=python3.9

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Raha Moosavi