Python modules, imports, packages, and virtual environments
Build a reliable mental model for Python imports, install packages into the correct interpreter, and prevent ModuleNotFoundError.
Before you start
- Python 3 is installed.
- You can open a terminal and run a Python file.
The import model
When Python evaluates an import, it searches the locations listed in sys.path. Those locations normally include the current project, the standard library, and the active interpreter's package directory.
import sys
for location in sys.path:
print(location)A package can be installed on your computer and still be unavailable to the project when pip and python point to different installations.
Confirm the active interpreter
Ask the interpreter for its exact executable path before installing anything.
python -c "import sys; print(sys.executable)"
python -m pip --versionThe two commands should describe the same Python installation. Prefer python -m pip over a bare pip command because it ties the package installer to the selected interpreter.
Create an isolated environment
python -m venv .venvActivate it on Windows PowerShell:
.\.venv\Scripts\Activate.ps1Activate it on macOS or Linux:
source .venv/bin/activateNow install and verify a dependency:
python -m pip install requests
python -c "import requests; print(requests.__version__)"Make the editor use the same Python
In VS Code, select the interpreter inside .venv. The terminal, debugger, test runner, and language server should all use that environment. If the terminal succeeds but the editor still reports a missing import, the selected editor interpreter is usually different.
Prevent the problem
Record project dependencies and recreate environments instead of sharing one global package directory.
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txtDo not commit the .venv directory. Commit the dependency file and setup instructions instead.
Errors this tutorial helps prevent
Frequently asked questions
The pip command probably belongs to a different Python installation. Compare python -m pip --version with the path printed by sys.executable.