Virtual Environments & pip Package Management

Module 1 • Session 03 • Allocation: 1 Contact Hr

venv pip PyPI requirements.txt

In professional Python development, different projects often require different versions of external libraries (e.g., Project A needs Django 3.2 while Project B requires Django 4.2). **Virtual environments** solve version conflicts by creating self-contained directory trees with isolated Python binaries and package site-packages.

1. What is a Virtual Environment?

A virtual environment is an isolated directory tree that contains a specific version of Python along with additional packages installed into its own isolated site-packages directory. This guarantees that project dependencies remain completely independent of the global system installation and other projects.

Why Global Package Installation is Dangerous: Installing packages globally via pip install package_name directly alters your machine's global site-packages directory. Upgrading a package for one project can easily break existing software running on your system.

2. Creating and Activating Virtual Environments (`venv`)

Python includes the built-in venv module out of the box. Follow these standard commands to set up an isolated environment:

# Step 1: Navigate to your project directory cd my_python_project # Step 2: Create a virtual environment named "env" (or ".venv") python -m venv env # Step 3: Activate the virtual environment # On Windows (Command Prompt): env\Scripts\activate.bat # On Windows (PowerShell): env\Scripts\Activate.ps1 # On macOS / Linux (bash/zsh): source env/bin/activate # Step 4: Deactivate when finished deactivate

3. Managing Packages with `pip` and PyPI

pip (Preferred Installer Program) connects to the Python Package Index (PyPI) to download, install, and manage third-party modules.

# Install the latest version of a package: pip install requests # Install a specific version: pip install requests==2.31.0 # List all packages installed in the active environment: pip list # Uninstall a package: pip uninstall requests -y

4. Reproducible Environments with `requirements.txt`

When collaborating or deploying code to production servers, you record dependency trees inside a requirements.txt file. This enables exact environment replication with a single command:

# Generate a manifest of all installed dependencies and exact versions: pip freeze > requirements.txt # Install all listed dependencies on a new machine or deployment environment: pip install -r requirements.txt

5. Programmatically Detecting Virtual Environment Activation

You can programmatically verify whether your script is executing inside a virtual environment by comparing sys.prefix with sys.base_prefix:

import sys def is_virtualenv_active(): return sys.prefix != sys.base_prefix print(f"Active Virtual Environment: {is_virtualenv_active()}") print(f"Current Sys Prefix: {sys.prefix}") print(f"Base Interpreter Prefix: {sys.base_prefix}")

šŸ‹ļø Try It Yourself: Practice Challenges

Challenge 1: Environment Isolation Diagnostics

Run the sandbox script below to detect if the Python execution context is executing in an isolated virtual environment or the global system space.

Challenge 2: Requirements File Parser

Extend the parser function to process version qualifiers like >=, ==, and extract package names into a dictionary map.

Challenge 3: Inspect site-packages Paths

Write a script using the site module to print all system and environment-specific package search directories.

⚔ Interactive Sandbox (Virtualenv Runtime Inspector)
Console Output:
Click "Run Code" above to execute interactive input scripts...

šŸ“ Knowledge Check Quiz

1. What is the primary purpose of creating a Python virtual environment?
2. Which command records all active environment packages into a shareable text file?
3. Which expression returns True when code is running inside a virtual environment?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)