Code 7: Virtual Environments

Setting up virtual environments to produce reproducible work
coding
python
Author

Tony Phung

Published

July 20, 2024

1. Virtual Environments

A virtual environment in Python is a self-contained directory that contains a Python installation and a set of packages.

This post will go through 3 methods to create virtual environments: - venv - conda virtual environments - pipenv

2. Purpose

Dependency Management:
- Different projects may require different versions of the same package.
- Virtual environments allow you to maintain these dependencies separately.

Isolation:
- Packages installed in a virtual environment are isolated from those installed system-wide or in other virtual environments
- Reducing the risk of version conflicts and compatibility issues.

Portability:
- A virtual environment can be easily replicated on another system by sharing the environment configuration file, such as requirements.txt.

3. Method 1: venv

mkdir proj && cd $_         # create proj1 and cd into proj1
python -m venv venv1        # run python module venv and create venv1
ls                          # note: venv1 folder is created (inside proj1)
source venv1/bin/activate   # activate venv1 by running bash script with source
(venv1)                     # note: (venv1) appears in front of (base) in terminal
pip freeze                  # note: no packages installed so no output
pip install sqalchemy       # install packages required
pip freeze                  # see list of packages installed
deactivate                  # deactivate venv1