How does Python find a module when you write import?
Python checks sys.modules for an already-loaded copy, then searches the directories in sys.path in order: the script's folder, PYTHONPATH entries, the standard library and site-packages. The first match wins, which is why a local file can shadow a library.
Explain it simply
Looking for a textbook: first check if you already took it out (sys.modules, the cache). If not, search your desk, then the class shelf, then the college library, in a fixed order. You stop at the first copy you find, even if a better one is in the library.
Example
import sys
print("math" in sys.modules) # Output: False
import math
print("math" in sys.modules) # Output: True
for p in sys.path[:2]:
print(type(p).__name__) # Output: str
# Output: str
print(math.__name__) # Output: mathThe first element of sys.path is usually the folder of the script being run, so a file named math.py there would be imported instead of the real math and break things. You can inspect where a module came from with module.__file__.
What to say in the interview
"Python first looks in sys.modules, the cache of loaded modules, then walks sys.path in order: the script directory, PYTHONPATH, the standard library and site-packages. The first match is used. That is why naming a file after a standard module causes confusing errors, and why a virtual environment changes which site-packages is used."
Common mistakes
- Editing
sys.pathin code to fix imports instead of structuring the project as a proper package.