How to fix pip ImportError: cannot import name 'main'

When using pip to install Python packages, you might encounter the following error:

ImportError: cannot import name 'main'

This error usually occurs after you upgraded pip to the latest version. There’s a breaking change in the pip code that causes this error.

This tutorial will show you an example that causes this error and how to fix it in practice.

How to reproduce this error

Suppose you called pip from the terminal to install any package as follows:

pip3 install requests

Output:

Traceback (most recent call last):
  File "/usr/bin/pip3", line 9, in <module>
    from pip import main
ImportError: cannot import name 'main'

The error happens because pip changed the internal file name from main.py to __main__.py. This causes Python to not be able to import the module.

How to fix this error

To resolve this error, you need to uninstall pip completely and install it again.

You can run the following command from the terminal:

# Mac/Linux:
pip uninstall pip
pip3 uninstall pip

python -m ensurepip --upgrade 
python3 -m ensurepip --upgrade 

# Windows:
py -m pip uninstall pip
py -m ensurepip --upgrade

The above command should uninstall and install a fresh pip build, so the previous incompatible build is removed.

Keep in mind that this way of installing pip doesn’t include it in the PATH environment variables. Running pip install would return pip command not found error.

This means that you need to use the python -m command to invoke pip from the terminal:

# Mac/Linux:
python -m pip install requests

# Windows:
py -m pip install requests

If you want to use pip directly from the terminal, you need to add the location of the program to the PATH environment variable.

If you use Homebrew to install your Python, you can try to unlink and link the python3 package as follows:

brew unlink python3 && brew link python3

If you’re on Windows, you need to install pip again with the following command:

py -m pip install --upgrade pip

Once finished, you should be able to run the pip commands directly:

$ pip -V
pip 23.0.1

Now you can use pip to install packages again. Nice work! 🙌

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.