Python Module Search Path

Summary: in this tutorial, you’ll learn how the module search path works in Python when you import a module into a program.

Introduction to Python module search path

When you import a module in a program:

import moduleCode language: Python (python)

Python will search for the module.py file from the following sources:

  • The current folder from which the program executes.
  • A list of folders specified in the PYTHONPATH environment variable, if you set it before.
  • An installation-dependent list of folders that you configured when you installed Python.

Python stores the resulting search path in the sys.path variable that comes from the sys module.

The following program shows the current module search path:

import sys

for path in sys.path:
    print(path)
Code language: Python (python)

Here’s a sample output on Windows:

D:\Python\
C:\Program Files\Python38\python38.zip
C:\Program Files\Python38\DLLs
C:\Program Files\Python38\lib
C:\Program Files\Python38
C:\Users\PythonTutorial\AppData\Roaming\Python\Python38\site-packages
C:\Program Files\Python38\lib\site-packages 
Code language: Shell Session (shell)

And the following is the sample output on Linux:

/Library/Frameworks/Python.framework/Versions/3.8/bin
/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip 
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.8/site-packagesCode language: Shell Session (shell)

To make sure Python can always find the module.py, you need to:

  • Place module.py in the folder where the program will execute.
  • Include the folder that contains the module.py in the PYTHONPATH environment variable. Or you can place the module.py in one of the folders included in the PYTHONPATH variable.
  • Place the module.py in one of the installation-dependent folders.

Modifying the Python module search path at runtime

Python allows you to modify the module search path at runtime by modifying the sys.path variable. This allows you to store module files in any folder of your choice.

Since the sys.path is a list, you can append a search-path to it.

The following example adds the d:\modules to the search path and use the recruitment module stored in this folder:

>>> import sys
>>> sys.path.append('d:\\modules\\')
>>> import recruitment
>>> recruitment.hire()
Hire a new employee...Code language: JavaScript (javascript)

Summary

  • When you import a module, Python will search for the module file from the folders specified in the sys.path variable.
  • Python allows you to modify the module search path by changing, adding, and removing elements from the sys.path variable.
Did you find this tutorial helpful ?