DevFixes
PythonBeginnerLanguage fundamentals

Python modules, imports, packages, and virtual environments

Build a reliable mental model for Python imports, install packages into the correct interpreter, and prevent ModuleNotFoundError.

20 min Published 2026-07-28

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.

python
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.

bash
python -c "import sys; print(sys.executable)"
python -m pip --version

The 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

bash
python -m venv .venv

Activate it on Windows PowerShell:

powershell
.\.venv\Scripts\Activate.ps1

Activate it on macOS or Linux:

bash
source .venv/bin/activate

Now install and verify a dependency:

bash
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.

bash
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt

Do 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.

References