Middle
How does Python search for modules during import?
sobes.tech AI
Answer from AI
Python searches for modules in the following order:
- Current directory of the executing script: Python first looks for the module in the directory where the script is located. This is the first entry in
sys.path. - Directories in the
PYTHONPATHenvironment variable: Next, Python searches directories specified in thePYTHONPATHenvironment variable. This is a list of paths separated by the system separator (e.g., colon on Unix-like systems or semicolon on Windows). - Standard Python installation directories: Python looks in standard directories where its libraries are installed. These paths are determined at Python build time and usually include paths to the
site-packagesdirectory. .pthfiles: Python can also use.pthfiles located in directories fromsys.path. These files contain additional paths that will be added tosys.pathwhen Python starts.
The order of directories in which Python searches for modules is stored in the sys.path list.
Example of viewing sys.path:
import sys
print(sys.path)
When a module is found, its code is loaded and executed, and then it becomes available under the name specified in the import statement. If the module is not found in any of these locations, a ModuleNotFoundError exception is raised. Before Python 3.6, this exception was called ImportError.