Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python as a system
EXPERIMENT 35 / 101

A clean room for dependencies.

Give each project its own installed packages and a repeatable starting point.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

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.

environments.py
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")
↳ EXPECTED OUTPUT
Running Python 3
matplotlib: installed
pymongo: installed
mysql-connector-python: installed

03 Under the hood

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

A SMALL MISSION

Print whether the running interpreter is inside a virtual environment.

Reveal one possible solution +
one_possible_solution.py
import sys
print(sys.prefix != sys.base_prefix)

05 Check your signal

QUICK SIGNAL CHECK

Why prefer python -m pip to an unrelated pip command?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.