A clean room for dependencies.
Give each project its own installed packages and a repeatable starting point.
01 The idea
A virtual environment isolates installed Python packages for one project. It does not replace the operating system or provide a security sandbox. Use the environment’s interpreter to run pip, so installing a package and running the program use the same Python. A dependency record documents what a collaborator needs; a production lock process should also capture transitive versions and platform constraints.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
import sys
from importlib.metadata import version, PackageNotFoundError
print(f"Running Python {sys.version_info.major}")
for package in ["matplotlib", "pymongo", "mysql-connector-python"]:
try:
version(package)
except PackageNotFoundError:
print(f"{package}: not installed")
else:
print(f"{package}: installed")Running Python 3 matplotlib: installed pymongo: installed mysql-connector-python: installed
03 Under the hood
- 1
Create an environment with python3 -m venv .venv, or py -m venv .venv on Windows. Activate it, then run python -m pip install -r requirements.txt from the downloaded workbench.
- 2
Activation adjusts your shell’s PATH. You can also invoke the environment interpreter directly without activation. Check python -m pip --version when debugging an installation mismatch.
- 3
The experiment reports package availability rather than hard-coding a version that could drift. Use the workbench verification command to check the installed environment against the examples.
04 Your turn, builder
Print whether the running interpreter is inside a virtual environment.
Reveal one possible solution +
import sys
print(sys.prefix != sys.base_prefix)05 Check your signal
Why prefer python -m pip to an unrelated pip command?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.