How to add a new path to your PYTHONPATH to import your own python modules or packages ?

Published: July 21, 2021

Tags: Python; PYTHONPATH; Python Module; Python Package;

DMCA.com Protection Status

Examples of how to add a new path to your PYTHONPATH to import your own python modules or packages:

Introduction

For example, I have on my local computer a reperestory called "github_projects" (located in the following path "/Users/John/github_projects") where I stored all my own python modules that I develop:

github_projects/
        project_01/
        project_02/
        project_03/
        .
        .
        .

However, if I try to import a python module from another reperestory on my computer I will get the following error message:

>>> import project_01
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'project_01'

We get this error message here because python doesn't know where to find the python module project_01. A simple solution to check that is to look at sys.path:

>>> import sys
>>> sys.path

returns for example in my case:

['', '/Users/John/anaconda3/lib/python36.zip', '/Users/John/anaconda3/lib/python3.6', '/Users/John/anaconda3/lib/python3.6/lib-dynload', '/Users/John/anaconda3/lib/python3.6/site-packages', '/Users/John/anaconda3/lib/python3.6/site-packages/aeosa']

can also check your PYTHONPATH using os:

>>> import os
>>> os.environ['PYTHONPATH']

Another solution to check your PYTHONPATH is to enter directly

echo $PYTHONPATH

in your terminal (not in your python interpreter!).

Adding a new path to your PYTHONPATH

To add a new path to your PYTHONPATH it is going to depend on the your shell (I used hereafter bash shell ). To get your shell just enter

echo $SHELL

returns for example

/bin/bash

To temporary add a new path in your PYTHONPATH:

export PYTHONPATH="/Users/John/github_projects"

then if you check

echo $PYTHONPATH

it should have now:

"/Users/John/github_projects"

and you can now start python (in the same window that you entered "export PYTHONPATH="/Users/John/github_projects") and try to import your module:

>>> import project_01

Another solution to make that more permanently just open the

.bash_profile

file and add the following line:

export PYTHONPATH="/Users/John/github_projects"

It will then add automatically "/Users/John/github_projects" to your PYTHONPATH each time you open a new terminal window.

Reloading your own python module

Note: another interessting tool is to be able to reload your python (> 3.4) module:

import importlib
importlib.reload(module)

So you don't need to restart python each time you make some change in your python module for example "project_01". You just need to reload it:

import importlib
importlib.reload(project_01)

References