Interview Q&A / Python

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How does Python find a module when you write import?

SHORT ANSWER

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

python
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: math

The 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.path in code to fix imports instead of structuring the project as a proper package.

#python#modules

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.