Saturday, October 8, 2022

[SOLVED] Package not importing in Colab after updating Python version

Issue

I'm currently working in Colab and trying to use a package that requires Python 3.9, but Colab runs natively on Python 3.7. I updated the Python version in Colab and installed the package as such:

#install python 3.9
!sudo apt-get update -y &> /dev/null
!sudo apt-get install python3.9 &> /dev/null

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

!sudo apt-get install python3-pip &> /dev/null
!sudo apt install python3.9-distutils &> /dev/null
!python3.9 -m pip install --upgrade pip &> /dev/null

# Install package
!python3.9 -m pip install mypackage

The only problem is that when I try

import mypackage

I get an ModuleNotFoundError saying that the module was not installed. I assume this is because Colab is looking in /usr/local/lib/python3.7/dist-packages/, rather than the corresponding path for python3.9.

Has anyone run into this issue / know what to do here? Any advice is greatly appreciated, thanks!


Solution

Well, after spending a little time on this problem, I finally found a workaround that might help you get over this problem. It might not be the best way to deal with the problem, but at least worked for me.

import sys

# Add the dist-package directory of Python3.8 to the path

sys.path.insert(0, '/usr/local/lib/python3.8/dist-packages/')


Answered By - Mahdi
Answer Checked By - Willingham (WPSolving Volunteer)