Sobes.tech
Middle

How does Python search for modules during import?

sobes.tech AI

Answer from AI

Python searches for modules in the following order:

  1. 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.
  2. Directories in the PYTHONPATH environment variable: Next, Python searches directories specified in the PYTHONPATH environment variable. This is a list of paths separated by the system separator (e.g., colon on Unix-like systems or semicolon on Windows).
  3. 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-packages directory.
  4. .pth files: Python can also use .pth files located in directories from sys.path. These files contain additional paths that will be added to sys.path when 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.