Python Virtual Environments (venv): Isolating Dependencies

Virtual environments are essential tools in Python development. They create isolated environments for Python projects, meaning that each project can have its own dependencies, regardless of what versions of libraries other projects (or the global Python installation) might be using. This prevents conflicts and makes dependency management much cleaner and more reproducible.

Python 3 comes with the venv module built-in, making virtual environment creation straightforward.

1. Creating a Virtual Environment

Navigate to your project’s root directory and create a virtual environment. It’s common practice to name the virtual environment directory .venv or venv.

python3 -m venv .venv
  • python3: Invokes the Python 3 interpreter.
  • -m venv: Runs the venv module as a script.
  • .venv: The name of the directory where the virtual environment will be created.

2. Activating the Virtual Environment

Before you can use the packages installed within your virtual environment, you need to activate it. Activation modifies your shell’s PATH variable to prioritize the virtual environment’s Python and pip executables.

source .venv/bin/activate

After activation, your shell prompt will typically change to indicate that you are inside the virtual environment (e.g., (.venv) user@host:~/my_project$).

3. Installing Dependencies

Once activated, you can install project-specific dependencies using pip. These packages will only be installed into the currently active virtual environment.

# Example: Install packages listed in a requirements.txt file
pip install -r requirements.txt

Or, to install individual packages:

pip install requests beautifulsoup4

4. Deactivating the Virtual Environment

When you are finished working in a virtual environment, you can deactivate it. This reverts your shell’s PATH to its original state.

deactivate

Your shell prompt will return to normal.

5. Deleting a Virtual Environment

To remove a virtual environment, simply delete its directory. There’s no special command for this; ensure you have deactivated it first.

deactivate # Make sure you're outside the .venv
rm -rf .venv

Workflow Summary

  1. Create project directory: mkdir my_project && cd my_project
  2. Create venv: python3 -m venv .venv
  3. Activate venv: source .venv/bin/activate
  4. Install dependencies: pip install -r requirements.txt (or individual packages)
  5. Work on your project.
  6. Deactivate venv: deactivate