The import mechanism is a fundamental part of Python. Many new developers find it simple at first, but as projects grow, understanding imports becomes more challenging. With several moving parts like where Python looks for modules and packages, it’s easy to run into issues. By the end of this article, you’ll learn key details that many Python developers overlook.
Table of Contents
Understanding PYTHONPATH
What is PYTHONPATH?
PYTHONPATH
is an environment variable that specifies additional directories for the Python interpreter to search for modules and packages. It acts as a supplement to Python’s default module search path, allowing you to include custom directories.
Let’s understand this with an example:
.
├── main.py
└── package
└── maths.py
Here’s our main.py
:
from maths import add, sub
print(add(1, 2))
print(sub(1, 2))
And our package/maths.py
:
def add(a, b):
return a + b
def sub(a, b):
return a - b
When we try to run this:
>>> python3 main.py
Traceback (most recent call last):
File "/home/user/python/pth/main.py", line 1, in <module>
from maths import add, sub
ModuleNotFoundError: No module named 'maths'
Python is looking for maths
in the current directory only:
['/home/user/python/pth',
'/usr/lib/python312.zip',
'/usr/lib/python3.12',
'/usr/lib/python3.12/lib-dynload',
'/usr/local/lib/python3.12/dist-packages',
'/usr/lib/python3/dist-packages']
Solutions
1. Temporary Changes Without Export
PYTHONPATH=./package python3 main.py
3
-1
2. Temporary Changes With Export
$ export PYTHONPATH=./package
$ python3 main.py
3
-1
3. Making Permanent Changes in PYTHONPATH
Add to your ~/.bashrc
or ~/.bash_profile
:
export PYTHONPATH=$PYTHONPATH:~/python/pth/package
Or use this command:
echo 'export PYTHONPATH=$PYTHONPATH:~/python/pth/package' >> ~/.bashrc
source ~/.bashrc
Alternative Code Solution
If you need to modify the path in code (though not recommended), you can do:
import sys
sys.path.append("./package")
from maths import add, sub
print(add(1, 2)) # Output: 3
print(sub(1, 2)) # Output: -1
Conclusion
Understanding PYTHONPATH
is crucial for Python developers. While it might seem simple, proper management of Python’s import system can prevent many common issues in larger projects. Remember:
PYTHONPATH
extends Python’s module search path- It can be modified temporarily or permanently
- Modifying it in code should be avoided when possible
- Always consider the implications for project portability
Whether you’re working on small scripts or large applications, a solid understanding of PYTHONPATH will help you avoid common pitfalls in Python development.