1.4.10Python & Scientific Computing

Virtual environments and pip - conda

2,258 words10 min readdifficulty · medium2 backlinks

The Core Problem: Dependency Hell

When you install Python packages globally (system-wide), you face:

  1. Version conflicts: Package A needs numpy 1.19, Package B needs numpy 1.24
  2. Pollution: Experimental packages clutter your system
  3. Reproducibility: "Works on my machine" → can't recreate exact environment
  4. Permission issues: System directories often need sudo/admin

Virtual environments solve this by creating isolated Python installations with their own package directories.

Figure — Virtual environments and pip - conda

How Virtual Environments Work (From Scratch)

Step 1: Understanding Python's Package Search Path

Python finds packages using sys.path, a list of directories searched in order:

import sys
print(sys.path)
# Output (typical):
# ['', '/usr/lib/python3.10', '/usr/lib/python3.10/site-packages', ...]

The trick: When you activate a virtual environment, it prepends the env's site-packages/ to sys.path. Now Python finds env packages first, ignoring system packages.

Step 2: Creating Isolation

When you create a venv:

  1. Python copies/symlinks the interpreter to venv/bin/python
  2. Creates empty venv/lib/python3.x/site-packages/
  3. Installs pip and setuptools into that directory
  4. Creates activate scripts that modify $PATH and $VIRTUAL_ENV

Why it works: The activate script does:

export PATH="/path/to/venv/bin:$PATH"
export VIRTUAL_ENV="/path/to/venv"

Now python resolves to venv/bin/python, which uses venv/site-packages/.

pip vs conda: Two Philosophies

pip (Python Package Installer)

Command syntax:

pip install package_name              # Latest version
pip install package_name==1.2.3       # Exact version
pip install -r requirements.txt       # From file
pip freeze > requirements.txt         # Export current packages

conda (Cross-Platform Package Manager)

Command syntax:

conda create -n myenv python=3.10     # Create env with Python version
conda activate myenv                  # Activate
conda install numpy scipy             # Install packages
conda env export > environment.yml    # Export

Derivation: Why requirements.txt Works

When you run pip install -r requirements.txt:

Step 1: pip reads each line (format: package==version or package>=version)

Step 2: For each package, pip:

  • Queries PyPI for available versions
  • Checks compatibility with Python version and installed packages
  • Resolves dependency tree (package A needs B, B needs C)

Step 3: Downloads in topological order (dependencies before dependents)

Step 4: Installs each package:

# Simplified pip install logic
def install_package(wheel_path, target_dir):
    with zipfile.ZipFile(wheel_path) as whl:
        whl.extractall(target_dir / 'site-packages')
        # Register in site-packages/ metadata

Why version pinning matters: Without ==, pip installs the latest version. Six months later, that version may have breaking changes → your code fails.

pip vs conda: Decision Guide

Aspect pip conda
Scope Python packages only Python + system libraries + interpreter
Repository PyPI (500k+ packages) Anaconda repos (~8k packages, curated)
Binaries Often source → needs compiler Pre-compiled binaries
Speed Fast for pure Python Slower (larger downloads, dependency solving)
Best for Web dev, general Python Data science, scientific computing

Rule of thumb: Use conda for data science (handles MKL, CUDA easily), pip for everything else.

Recall Explain to a 12-Year-Old

Imagine you're building two LEGO projects: a castle and a spaceship. You have one big bin of LEGOs. Every time you switch projects, you have to dig through the bin to find the right pieces. Sometimes you lose pieces, or use a spaceship piece in the castle by mistake.

Virtual environments are like having two separate bins. When you work on the castle, you only see castle LEGOs. When you work on the spaceship, you only see spaceship LEGOs. No mixing, no confusion.

pip is like ordering LEGOs from a catalog—you pick exactly what you want. conda is like getting a pre-built LEGO kit with batteries, motors, and instructions included. Conda is more convenient but bigger boxes.

Connections

  • 1.4.1-Python-basics-syntaxand-data-types - Understanding modules and import system
  • 1.4.8-File-IOand-data-serialization - Reading requirements.txt and environment.yml
  • 1.5.1-NumPy-arrays-and-vectorization - NumPy often installed venvs, shows import behavior
  • 2.1.3-Setting-up-development-environment - Practical application of venvs in ML workflows
  • 1.4.12-Profiling-and-optimization - Isolated environments for benchmarking

#flashcards/ai-ml

What is a virtual environment? :: An isolated Python installation with its own package directory (site-packages), preventing version conflicts between projects.

How does activating a venv modify Python's behavior?
It prepends the venv's bin/ directory to $PATH and site-packages/ to sys.path, so python and pip resolve to venv versions first.
What is the key difference between pip and conda?
pip manages Python packages only from PyPI; conda manages Python interpreter + system libraries (CUDA, MKL) + Python packages, using pre-compiled binaries.
Command to create a venv using Python's built-in module?
python3 -m venv <env_name>
Command to export pip packages with exact versions?
pip freeze > requirements.txt
Command to recreate a pip environment on another machine?
pip install -r requirements.txt
Why should you always pip install after activating the environment?
To ensure packages install to the venv's site-packages, not globally. Prevents "works on my machine" issues and ensures requirements.txt is accurate.

What does conda env export capture that pip freeze doesn't? :: The Python version, conda packages, system libraries, and pip packages—everything needed to recreate the environment completely.

Concept Map

includes

includes

solves

contains

uses

prepends env to

makes Python find

installs into

downloads from

manages only

alternative to

manages system libs plus Python

Dependency Hell

Version Conflicts

Reproducibility Issues

Virtual Environment

Isolated site-packages

Activate Script

sys.path

pip

conda

PyPI

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Virtual environments ka main kaam hai package conflicts ko rokna. Socho tumhare pas do ML projects hain - ek purana jo TensorFlow 2.10 use karta hai, dosra naya jo TensorFlow 2.15 chahiye. Agar tum globally install karoge (pore system mein), toh dono projects ek hi package version use karenge aur ek project zaroor break ho jayega. Virtual environmentek separate "bubble" banata hai har project ke liye - apna Python installation, apne packages, koi mixing nahi.

pip aur conda dono virtual environments manage karte hain, lekin unka scope alag hai. pip sirf Python packages install karta hai (jaise numpy, pandas) PyPI repository se.Agar tumhe system libraries chahiye (jaise CUDA for GPU computing, ya Intel MKL for fast math), toh woh alag se install karni padegi. conda zyada powerful hai - woh pura environment manage karta hai including Python interpreter, system libraries, aur packages. Data science ke liye conda better hai kyunki numpy, scipy sabke sath optimized MKL binaries ate hain automatically. General Python development ke liye pip lightweight aur fast hai.

Commands yad rakhne ka tarika: python3 -m venv myenv se venv banao (Python built-in hai), phir source myenv/bin/activate se activate karo (Windows mein myenv\Scripts\activate). Ab jo bhi pip install karoge woh sirf is environment mein jayega. pip freeze > requirements.txt se sab packages ki list export karo exact versions ke sath - ye file teammate ko doge toh woh pip install -r requirements.txt se exactly same environment bana sakta hai. conda ke liye conda create -n myenv python=3.10 aur conda activate myenv use karo.

Sabse common mistake: venv activate karna bhool jana. Agar tum naye terminal mein code run karo bina activate kiye, toh Python system packages use karega, environment wale nahi. Hamesha check karo ki terminal prompt mein environment naam dikhe (jaise (myenv) $) - yahi signal hai ki tum sahi environment mein ho. Dosra mistake: packages globally install karna phir venv bane ke bad unhe use karna. Ye accidental isolation break karta hai aur reproducibility issues deta hai bad mein.

Go deeper — visual, from zero

Test yourself — Python & Scientific Computing

Connections