Lesson 14: Virtual Environments and Dependency Management

How to isolate Python projects and manage external libraries

Why Virtual Environments Matter

Different Python projects often require different versions of packages. A virtual environment creates an isolated workspace so dependencies don’t conflict with each other or with system‑wide Python installations.

Creating a Virtual Environment

Use Python’s built‑in venv module:

python -m venv venv

Activating the Environment

Windows:

venv\Scripts\activate

macOS/Linux:

source venv/bin/activate

Deactivating the Environment

deactivate

Installing Packages

Once the environment is active, use pip to install packages:

pip install requests
pip install flask

Viewing Installed Packages

pip list

Freezing Dependencies

Save all installed packages to a file:

pip freeze > requirements.txt

Installing from requirements.txt

Recreate the same environment elsewhere:

pip install -r requirements.txt

Upgrading and Uninstalling Packages

pip install --upgrade requests
pip uninstall flask

Using pipx for Global Tools

pipx installs Python tools globally but isolates them in their own environments:

pip install pipx
pipx install black

Best Practices

Next Steps

Now that you can manage environments and dependencies, you're ready to explore how to work with external libraries in Lesson 15: Working with External Libraries (pip).

← Back to Lesson Index