Virtual Environments and Dependencies
Give each project a predictable interpreter and dependency workflow without confusing activation, installation, and reproducibility.
By the end, you’ll be able to…
- Create and identify a project virtual environment.
- Run pip through the intended interpreter.
- Document dependencies and distinguish a project manifest from an environment snapshot.
01An environment isolates project installations
A virtual environment provides a project-specific Python environment with its own installation locations. It helps one project use a dependency version without changing another project’s environment. It does not sandbox the program from your files or network, and it does not package the operating system.
Create an environment using the interpreter version you intend to support. A conventional .venv directory lives beside project source and is excluded from version control. Environments are disposable: preserve the instructions and dependency records needed to recreate one, rather than copying its directory between machines.
# Run in your project directory with Python 3.12 or later.python -m venv .venv# Windows: use the environment interpreter directly..venv\Scripts\python.exe --version.venv\Scripts\python.exe -m pip --version# macOS/Linux equivalents:.venv/bin/python --version.venv/bin/python -m pip --version02Activation changes command lookup
Activation adjusts your shell environment so a short python command resolves to the environment interpreter. It is a convenience, not a required step. You can always run the environment interpreter by its path, which is especially useful in scripts and when activation is restricted by shell policy.
Use python -m pip through the intended interpreter instead of trusting an unrelated pip command on PATH. To diagnose confusion, inspect sys.executable and pip --version using that same interpreter. An editor can select a different interpreter from the terminal, so confirm its project configuration as well.
import sysprint("Interpreter:", sys.executable)print("In virtual environment:", sys.prefix != sys.base_prefix)print("Python:", ".".join(map(str, sys.version_info[:3])))03Record intent separately from a snapshot
A pyproject.toml file can describe a distributable project’s supported Python version and direct runtime dependencies. A requirements file is input for pip and may pin exact versions for an application environment. Their purposes overlap, but a list of everything currently installed is not automatically a carefully designed dependency policy.
pip freeze records installed packages and versions, including transitive dependencies that your code may never import directly. This can help reproduce a known application environment, but it does not capture the Python interpreter, operating-system libraries, or every platform constraint. Review changes and test a clean recreation instead of assuming a frozen list proves portability.
[project]name = "study-task-tracker"version = "0.1.0"requires-python = ">=3.12"dependencies = []04Practice a clean recreation workflow
For a small script repository, document the supported Python version, environment command, run command, and test command in its README. If external packages are later introduced, declare the direct dependencies and choose a suitable repeatable installation workflow. Avoid importing a package merely because it happens to exist globally on your development machine.
When an installation fails, first verify interpreter selection, network access, and platform support rather than repeatedly installing into different locations. Do not run arbitrary installation commands copied from untrusted output. A dependable project can be recreated in a fresh environment using its documented inputs, and its tests confirm that the resulting combination works. Recreate periodically to catch undocumented dependencies before a teammate encounters them.
# Example application workflow if a reviewed requirements.txt exists.# Installation may access the package index and is not needed for course examples.python -m venv .venv.venv\Scripts\python.exe -m pip install -r requirements.txt.venv\Scripts\python.exe -m unittest discover -s tests -v# For a standard-library-only script, simply run it:.venv\Scripts\python.exe tracker.py --helpThe ideas worth keeping.
- Treat environments as disposable project infrastructure.
- Use the intended Python interpreter for running and installing.
- Verify recreation rather than equating a package list with portability.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Diagnose two interpreters
Your editor imports a package but the terminal cannot. Write a diagnostic script and describe how you would compare the editor and terminal results before installing anything.
Explore a worked solution
import sysimport sysconfigprint("Executable:", sys.executable)print("Version:", sys.version.split()[0])print("Package directory:", sysconfig.get_paths()["purelib"])print("Environment active:", sys.prefix != sys.base_prefix)Run the same script from both launch locations and compare executable paths and package directories. Select the intended environment in the editor and invoke its Python explicitly in the terminal; then use that interpreter’s -m pip if installation is actually required.
Write a recreation recipe
Create a command recipe for a standard-library-only project containing tracker.py and tests/. Include interpreter verification and test discovery without installing packages.
Explore a worked solution
python -m venv .venv.venv\Scripts\python.exe --version.venv\Scripts\python.exe -m unittest discover -s tests -v.venv\Scripts\python.exe tracker.py --helpThese are Windows shell commands, not Python statements. On macOS/Linux replace the interpreter path with .venv/bin/python. The recipe verifies the chosen interpreter, runs tests, and checks the CLI entry point; no external dependency installation is needed.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Diagnose two interpreters
Your editor imports a package but the terminal cannot. Write a diagnostic script and describe how you would compare the editor and terminal results before installing anything.
Executable: sys.executable Version: sys.version.split()[0] Package directory: sysconfig.get_paths()["purelib"] Environment active: True
Keep exploring.
The official references behind this chapter, when you want a second angle or the full details.
Pause. Put the pieces together.
You’ve reached the end of Practical Standard Library Tools. Before moving on, use this task to check what you can do independently.
Choose an appropriate collection, handle an aware timestamp, and document how to recreate the project environment.
Try it in your own environment and write down the result. This is a self-check; reading completion does not evaluate your code.
Review this moduleOne chapter closer.
Reading is a start. Trying it yourself makes the connection.