
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Locating Modules in Python
Locating modules in Python refers to the process of how Python finds and loads a module into our current program when we are trying to import it. Python's standard library comes with a large number of modules that we can use in our programs with the import statement.
Locating Modules in Python
When you write an import statement like import mymodule, the Python interpreter searches for the module in the following sequences:
- The current directory: Python first checks the directory of the current script.
- PYTHONPATH Environment Variable: If the module isn't found in the current working directory, Python then searches each directory in the shell variable PYTHONPATH.
- Default Install Locations: If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.
These module search paths are stored in the built-in sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.
The sys.path Variable
Python stores the complete module search path in a list as the sys.path variable, which comes from the built-in sys module.
Example
The following example shows how to retrieve the list of module search paths using the sys.path variable.
# import the sys module import sys print(sys.path)
While executing the above program we get the following output:
['/home/cg/root/682c9745587be', '/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']
This resultant list contains the current working directory, any additional directories listed in the PYTHONPATH environment variable, and standard system directories for built-in and third-party modules.
The PYTHONPATH Variable
The PYTHONPATH is an environment variable that consists of a list of directories. Python adds these directories to the module search path when it starts. The syntax of PYTHONPATH is the same as that of the shell variable PATH .Here is a typical PYTHONPATH from a Windows system:
set PYTHONPATH = c:\python20\lib;
And the syntax of the PYTHONPATH variable in UNIX system is:
set PYTHONPATH = /usr/local/lib/python
It helps us to add custom directories to Python's module search path without modifying our program.