Managing Dependencies with Python Virtual Environments

Python Logo

A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project separately from other projects. This prevents conflicts and ensures your project has the correct versions of the packages it needs.

Why Use Them?

Imagine you have two projects: Project A needs version 1.0 of a library, while Project B needs version 2.0. Installing both system-wide would cause conflicts. Virtual environments solve this by creating a self-contained space for each project.

Using `venv`

Python's built-in `venv` module is the standard way to create virtual environments.

# 1. Create a virtual environment named 'env'
python -m venv env

# 2. Activate the environment
# On Windows:
# env\Scripts\activate
# On macOS/Linux:
# source env/bin/activate

# 3. Install dependencies (they will be installed in the 'env' folder)
pip install requests

# 4. Deactivate the environment when you're done
deactivate

It's a best practice to create a `requirements.txt` file to keep track of your project's dependencies: `pip freeze > requirements.txt`.

Comments