How does Python find a module when you write `import something`, and what role does `sys.path` play?
Answer
On `import something`, Python first checks `sys.modules` to see if the module was already imported and cached; if not, it searches the directories listed in `sys.path`, in order, until it finds a matching module or package. `sys.path` starts with the directory of the running script (or the current directory), then entries from the `PYTHONPATH` environment variable, then the standard library and installed site-packages locations; whichever matching file is found first wins, which is exactly why a locally-named file that shadows a standard-library or installed module name (like `random.py` in your own project) can silently break unrelated imports.
Strong answer includes
- checks sys.modules cache first, then searches sys.path directories in order
- sys.path includes the script's directory, PYTHONPATH, stdlib, site-packages
- first match wins, so a local file can shadow a standard-library module name
Practical example
Creating a personal script named `json.py` in a project's root directory can silently break every later
import jsonin that same directory, because the local file is found in `sys.path` before the standard library's `json` module.