Virtual Environments

 


The primary goal is to provide isolation. Without virtual environments, you install libraries "globally," which can lead to "Dependency Hell"—where Project A needs Version 1 of a library, but Project B needs Version 2, and installing one breaks the other.


1. Why Do You Need Them?

  • Version Control: Different projects can use different versions of the same library (e.g., Django 3.2 for an old project and Django 5.0 for a new one).

  • System Cleanliness: It prevents you from cluttering your computer's main Python installation with hundreds of experimental packages.

  • Reproducibility: By using an environment, you can easily export a list of your exact dependencies so another developer can recreate your setup perfectly.


2. Standard Tools

There are several ways to manage environments, but these three are the most common:

ToolBest ForDescription
venvGeneral UseThe built-in Python module. Lightweight and standard.
CondaData ScienceManages both Python and non-Python dependencies (like C++ libraries).
PoetryProfessional DevA modern tool that handles both environments and package publishing.

3. The Lifecycle of a Virtual Environment

Using the built-in venv module, the workflow typically follows these four steps:

Step 1: Creation

Navigate to your project folder in the terminal and run:


python -m venv .venv

(Note: .venv is the standard name for the folder where the environment data is stored.)

Step 2: Activation

You must "enter" the environment to use it.

  • Windows: .venv\Scripts\activate

  • macOS/Linux: source .venv/bin/activate

Step 3: Installation

Once activated, any package you install stays inside that folder:


pip install requests

Step 4: Deactivation

When you are finished, simply type:


deactivate

4. Portability: requirements.txt

Since virtual environment folders are quite large, we never share the folder itself (and we always add it to .gitignore). Instead, we share a "manifest" file.

  1. To Save: pip freeze > requirements.txt (This lists everything you've installed).

  2. To Recreate: A friend can download your code and run pip install -r requirements.txt to get the exact same setup.


Summary: Best Practices

  • One Project, One Environment: Always create a new environment for every new project.

  • Don't Sudo: Never use sudo pip install. If you find yourself needing it, you should probably be using a virtual environment instead.

  • Gitignore: Always add your environment folder (e.g., venv/ or .venv/) to your .gitignore file.

Would you like me to show you how to configure VS Code to automatically detect and use your virtual environment when you open a project?

Post a Comment

0 Comments