Wednesday, October 15, 2025

Virtual Environments in Programming: Core Concept

 Virtual Environments in Programming: Core Concept

A virtual environment (often called "venv") is an isolated workspace for a Python project. It creates a self-contained directory with its own Python interpreter and installed packages, preventing conflicts between projects (e.g., one app needs Django 3.0, another needs 4.0). This is crucial for dependency management, reproducibility, and avoiding "dependency hell" on shared systems.Why Use Them?
  • Isolation: Packages don't interfere globally.
  • Reproducibility: Share requirements.txt for exact setups.
  • Cleanliness: Easy to delete and recreate without affecting the system Python.
Virtual environments are built-in in Python 3.3+ via the venv module; older versions use virtualenv (third-party tool).Key Components
Component
Description
Example
venv Directory
Root folder holding the environment (e.g., myenv/). Contains bin/ (scripts), lib/ (packages), and pyvenv.cfg.
myproject/myenv/
Activation Script
Shell script to "enter" the env (adds it to PATH).
source myenv/bin/activate (Unix) or myenv\Scripts\activate (Windows)
Deactivation
Exits the env, reverting to system Python.
deactivate
Requirements File
Lists dependencies for recreation.
pip freeze > requirements.txt then pip install -r requirements.txt
How to Create and Use (Python Example)
  1. Create:
    bash
    python -m venv myenv  # Creates 'myenv' folder
  2. Activate:
    • Unix/macOS: source myenv/bin/activate
    • Windows: myenv\Scripts\activate
    (Your prompt changes to (myenv) indicating activation.)
  3. Install Packages (isolated to this env):
    bash
    pip install requests django  # Only affects this env
  4. Run Code:
    python
    # In a script or REPL
    import requests  # Works because it's installed here
    print(requests.__version__)
  5. Deactivate:
    bash
    deactivate
  6. Delete/Recreate: Just remove the folder (rm -rf myenv) and start over.
Advanced Tips
  • IDE Integration: Tools like VS Code or PyCharm auto-detect and activate venvs.
  • Alternatives: conda for Anaconda users (handles non-Python deps too); poetry or pipenv for modern dependency management.
  • Global vs. Local: Always prefer venvs over sudo pip install to avoid system pollution.
If this is about virtual machines (e.g., VMware), cloud envs, or another context, clarify! Want a step-by-step demo for a specific OS? Let me know.

Lecture Notes: Optimising Numerical Code

Lecture Notes: Optimising Numerical Code Prerequisites: Basic Python programming Understanding of NumPy arrays and vector ...