Python

A Virtual Environment is an isolated workspace for a Python project. It allows you to install specific versions of libraries (like NumPy or Pandas) for one project without affecting other projects or the global Python installation on your computer.

1. Theoretical Overview

Why do we need Virtual Environments?

Imagine you are working on two projects:

  • Project A: Uses an old version of a library (e.g., Django 2.0).

  • Project B: Uses the latest version (e.g., Django 5.0).

If you install these globally, one will overwrite the other, breaking your code. A Virtual Environment solves this by creating a separate folder that contains its own copy of the Python executable and its own site-packages (where libraries are stored).

Key Benefits

  • Dependency Management: Avoid "dependency hell" where different projects require conflicting library versions.

  • Reproducibility: You can generate a list of all requirements (using requirements.txt) so another developer can recreate your exact environment.

  • System Protection: Prevents you from accidentally breaking the Python version used by your Operating System (especially critical on Linux and macOS).

2. Practical Workflow (The Commands)

Python comes with a built-in module called venv to handle this.

Step 1: Create the Environment

Open your terminal or command prompt inside your project folder and run:

Bash
# 'myenv' is the name of the folder that will be created
python -m venv myenv

Step 2: Activate the Environment

You must "enter" the environment to use it. The command varies by Operating System:

  • Windows: myenv\Scripts\activate

  • macOS / Linux: source myenv/bin/activate

Once activated, you will usually see (myenv) appear in parentheses at the start of your command prompt.

Step 3: Install Packages

Now, any package you install via pip stays inside this environment.

Bash
pip install requests

Step 4: Deactivate

When you are done working, simply type:

Bash
deactivate

3. Managing Requirements

To share your project with others, you record your environment's state into a text file.

Bash
# Save all installed libraries to a file
pip freeze > requirements.txt

# Someone else can install everything at once using:
pip install -r requirements.txt

4. Summary Table

ActionCommand (General)
Createpython -m venv <env_name>
Activate (Windows)<env_name>\Scripts\activate
Activate (Mac/Linux)source <env_name>/bin/activate
Check Installedpip list
Exitdeactivate
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now