Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / Python Tutorial / Chapter 6: Practical Projects & Working with Libraries
PYTHON ⏱ 10 min read

Working with Libraries: Virtual Environments and pip

Professional Python developers never install packages into their global Python installation. Virtual environments keep project dependencies isolated.

What is it?

A Python virtual environment is an isolated directory tree containing a Python installation for a specific version, along with additional packages.

Why is it used?

Prevents version conflicts between different projects (e.g. Project A needing Flask 2.0 while Project B needs Flask 3.0).

Detailed Explanation

Standard Virtual Environment Workflow: 1. Create: `python -m venv venv` 2. Activate (Windows PowerShell): `.\venv\Scripts\Activate.ps1` Activate (Mac/Linux): `source venv/bin/activate` 3. Install packages: `pip install flask requests supabase` 4. Freeze dependencies: `pip freeze > requirements.txt` 5. Install from requirements: `pip install -r requirements.txt` 6. Deactivate: `deactivate`

Syntax Structure

Syntax Blueprint
# Terminal workflow
python -m venv venv
.\venv\Scripts\activate
pip install -r requirements.txt

Code Example

PYTHON Code
# Inspecting Virtual Environment in Python Code
import sys
import os

print("=== Python Environment Info ===")
print("Python Executable:", sys.executable)
print("Python Version:   ", sys.version.split()[0])

# Detect if running inside a virtual environment
in_venv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
print("Inside Virtualenv:", in_venv)

Explanation of the Code

• `sys.executable` displays the active Python binary. • Evaluates whether code is running inside an isolated virtual environment.

Expected Output

=== Python Environment Info === Python Executable: ...\python.exe Python Version: 3.14.3 Inside Virtualenv: ... (True/False)

Real-World Application

Every production Python deployment (Heroku, AWS, Docker) relies on virtual environments and `requirements.txt`.

Common Mistakes to Avoid

• Committing the `venv/` folder into Git (never commit virtual environments! Always add `venv/` to `.gitignore`). • Forgetting to activate the virtual environment before installing packages with `pip`.

Quick Practice Challenge

Inspect the root `requirements.txt` of this IGM Computers project to see the installed dependencies.

Key Takeaways

• Always create a virtual environment with `python -m venv venv`. • Always add `venv/` to your `.gitignore`. • Use `pip freeze > requirements.txt` to lock project dependencies.