Python Path
Table of contents
Intro
Recently, a colleague was refactoring her Python config and setting up uv. She was trying to use our connectors to our databases and it did not work. In the end, the solution was to add the root of our repository in her PYTHONPATH. But it took me some time to figure it, which had me realizing that I did not really understand what the PYTHONPATH was. So I decided to learn about it, and write here my discoveries.
So to be clear, this article will not be very organized, it’s more of a collection of notes and remarks.
What is it ?
PYTHONPATH is an environment variable, which means a key-value pair. In Unix, we can retrieve them using $ before it’s name, and in Windows $env:.
echo $PYTHONPATHecho $env:PYTHONPATHMore specifically, this variable should contain a path telling the Python interpreter where to find libraries and applications.
Here is the list of Python’s environment variables.
import sys
sys.pathsys.path is a Python list that starts with the PYTHONPATH and then others depending on python installation. So when importing a module, the Python interpreter will look for it in this list, starting from the folder designated in the PYTHONPATH environment variable.
This explains how I could help my colleague. We work in a big repository, something like this :
repo
└── app
├── noprod
│ └── etude
│ └── main.py
└── utils
└── very_usefull_script.pyIn her script main.py, she needed to use a function defined in the very_usefull_script.py. So she was doing from app.utils.very_usefull_script import important_function and it could not find he function.
So I added the path to the repo in her PYTHONPATH and it solved the problem. Because then, when the Python interpreter was looking for app in sys.path, it knew it had to look in the repository.
If I understand correctly, it means that instead of adding the path to the repo I could have added directly the path to repo/app/utils to the PYTHONPATH, and so she could have done from very_usefull_script import important_function.
Additional remark: in most instances, PYTHONPATH does not need to be set. Only if I need to import a custom module.
Conclusion
I know all this is probably very trivial for anyone reading this article, but all this made me realize that I had been using Python for years (decade !) without never really understanding what the PYTHONPATH was and that import was not magic, just looking in the good place for what I needed.