Skip to main content

Modules & Files

pip & Virtual Environments

Complete lesson for pip & Virtual Environments using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — pip & Virtual Environments

Section: Modules & Files. pip and virtual environments — isolate dependencies with venv, install packages with pip, freeze requirements, and avoid polluting the system Python.

Why virtual environments?

  • Different projects need different package versions. Isolating them prevents conflicts.
  • A venv has its own site-packages and its own python / pip executables.
  • Real-life analogy: each project gets its own toolbox instead of one shared messy drawer.
ProblemWithout venvWith venv
Version clashProject A needs requests 2.x, B needs 1.xEach env has its own copy
System PythonEasy to break OS toolsLeaves system site-packages alone
ReproducibilityHard to know what was installedrequirements.txt pins versions
Collaboration"Works on my machine"Same install steps for everyone

Create a venv with the standard library

  • python -m venv .venv creates an environment in .venv/ (common convention).
  • The stdlib venv module is enough for most beginners; the third-party virtualenv tool is an alternative with extra features.
  • Always create venvs per project, not one global shared venv for everything.
# Commands (run in a terminal, not inside another unclear env):
# python -m venv .venv
# Windows PowerShell:  .\.venv\Scripts\Activate.ps1
# Windows cmd:         .\.venv\Scripts\activate.bat
# macOS / Linux:       source .venv/bin/activate
# deactivate

Activation differences by OS

  • Activation only adjusts PATH for your shell session.
  • You can skip activation and call .venv/Scripts/python.exe -m pip install ... directly.
ShellActivatepython location
PowerShell.\.venv\Scripts\Activate.ps1.venv\Scripts\python.exe
cmd.exe.\.venv\Scripts\activate.bat.venv\Scripts\python.exe
bash/zshsource .venv/bin/activate.venv/bin/python
No activateCall the interpreter by pathSame as above

pip essentials

  • Prefer python -m pip so you install into the same interpreter you run.
  • pip install package, pip install package==1.2.3, pip install -r requirements.txt.
  • pip list, pip show package, pip uninstall package.
CommandPurpose
python -m pip install requestsInstall latest compatible version
python -m pip install requests==2.32.3Pin exact version
python -m pip install -r requirements.txtInstall from file
python -m pip freeze > requirements.txtExport pinned set
python -m pip listShow installed distributions
python -m pip show pipMetadata for one package
python -m pip install -U pipUpgrade pip itself

requirements.txt basics

  • A text file listing distributions and optional version specifiers.
  • pip freeze outputs exact pins (pkg==1.2.3) — great for apps; libraries often use broader ranges.
  • Commit requirements.txt (or lock files) so teammates and servers install the same stack.
# Example requirements.txt
# requests==2.32.3
# rich>=13.0
# # comments start with #

Typical project workflow

  • 1) Create venv 2) Activate 3) Upgrade pip 4) Install deps 5) Freeze when stable.
  • Add .venv/ to .gitignore — never commit the environment folder.
  • Document Python version (e.g. 3.12+) in README.
StepCommand
Createpython -m venv .venv
Activate (PS).\.venv\Scripts\Activate.ps1
Upgrade pippython -m pip install -U pip
Installpython -m pip install -r requirements.txt
Freezepython -m pip freeze > requirements.txt
Leave envdeactivate

venv vs virtualenv vs conda

  • This lesson focuses on venv + pip — the baseline every Python developer should know.
ToolComes withNotes
venvStdlibDefault choice for pure Python apps
virtualenvPyPI packageFaster/older support; similar UX
conda/mambaAnaconda ecosystemAlso manages non-Python binaries
poetry/uv/pipenvThird-partyHigher-level dependency workflows

Where packages land

  • Inside a venv, installs go to .venv/Lib/site-packages (Windows) or .venv/lib/pythonX.Y/site-packages.
  • import site; site.getsitepackages() shows candidate directories.
  • If pip and python disagree, you installed into the wrong environment.
import sys
import site

print("executable:", sys.executable)
print("prefix:", sys.prefix)
print("site-packages:")
for p in site.getsitepackages():
    print(" ", p)
L2

Advanced — pip & Virtual Environments

Programmatic venv creation

  • The venv module can create environments from Python code (venv.EnvBuilder).
  • Useful for tooling and teaching demos; day-to-day use is still the CLI.
import venv
from pathlib import Path

env_dir = Path("mini_env")
builder = venv.EnvBuilder(with_pip=True)
builder.create(env_dir)
print("created:", env_dir.resolve())
print("pyvenv.cfg exists:", (env_dir / "pyvenv.cfg").exists())

Pinning strategies

  • Apps: pin exact versions with pip freeze for reproducible deploys.
  • Libraries: specify minimums / compatible ranges; let apps pin.
  • Separate requirements.txt (runtime) and requirements-dev.txt (pytest, linters).

Common pip failures

  • Permission errors → you are installing into system Python; use a venv.
  • Wrong package installed → ran pip from a different interpreter than python.
  • Build errors → package needs compilers or a wheel for your platform/Python version.
SymptomLikely causeFix
command not found: pipScripts not on PATHpython -m pip ...
Installs but import failsMultiple PythonsCompare sys.executable
SSL / network errorsProxy or offline networkFix network or use wheels cache
Conflict resolutionsIncompatible pinsRelax pins or align versions

Editable installs

  • pip install -e . installs your project in editable mode so code changes apply without reinstall.
  • Needs packaging metadata (pyproject.toml or setuptools config).
  • Best way for local package development — better than sys.path hacks.

Security and trust basics

  • Prefer well-known packages; check PyPI project pages and download stats.
  • Pin versions in production; review upgrades.
  • Use private indexes carefully; configure pip index URL only when required.

Reading environment markers

  • Requirements can include environment markers: package; python_version>="3.10".
  • Useful for OS-specific or version-specific dependencies.
# Example line for requirements files:
# pywin32>=306; sys_platform == "win32"
L3

Tricky Interview Points

Q1) What is a virtual environment?

Answer An isolated directory with its own Python interpreter and site-packages so project dependencies do not clash.

Q2) How do you create and activate a venv?

Answer python -m venv .venv, then run the OS-specific Activate script under .venv/Scripts (Windows) or source .venv/bin/activate (Unix).

Q3) Why prefer python -m pip over bare pip?

Answer It guarantees the pip module runs with that same Python interpreter, avoiding installs into the wrong environment.

Q4) What is requirements.txt?

Answer A file listing dependencies (often pinned) that pip install -r can reproduce.

Q5) What does pip freeze do?

Answer Lists installed distributions as package==version pins, commonly redirected into requirements.txt.

Q6) Should you commit .venv to git?

Answer No. Commit requirements or lock files; recreate the venv on each machine.

Q7) venv vs virtualenv?

Answer venv is in the standard library. virtualenv is a third-party tool with similar goals and some extra features/older Python support.

Q8) How do you upgrade pip inside a venv?

Answer python -m pip install -U pip

Q9) What is an editable install?

Answer pip install -e . links your project into site-packages so local edits are imported immediately.

Q10) Import works in the IDE but not in the terminal — why?

Answer Different interpreters/environments. Compare sys.executable and which pip is on PATH.

Q11) How do you uninstall a package?

Answer python -m pip uninstall package_name

Q12) What is site-packages?

Answer The directory where third-party distributions are installed and searched during import.

L4

Simple Programs

Show interpreter and site-packages

import sys
import site

print("executable:", sys.executable)
print("version:", sys.version.split()[0])
print("prefix:", sys.prefix)
print("base_prefix:", getattr(sys, "base_prefix", sys.prefix))
print("in_venv:", sys.prefix != getattr(sys, "base_prefix", sys.prefix))
for p in site.getsitepackages():
    print("site:", p)

Create a venv folder with venv.EnvBuilder

import venv
from pathlib import Path

env_dir = Path("pyv_demo_env")
if not env_dir.exists():
    venv.EnvBuilder(with_pip=True).create(env_dir)
cfg = (env_dir / "pyvenv.cfg").read_text(encoding="utf-8")
print(cfg.splitlines()[0])
print("Scripts/bin exists:", (env_dir / "Scripts").exists() or (env_dir / "bin").exists())

Write and parse a requirements.txt

from pathlib import Path

req = Path("sample_requirements.txt")
req.write_text(
    "# demo requirements\n"
    "requests==2.32.3\n"
    "rich>=13.0\n"
    "pytest; extra == 'dev'\n",
    encoding="utf-8",
)

def parse_requirements(text: str) -> list[str]:
    out: list[str] = []
    for line in text.splitlines():
        s = line.strip()
        if not s or s.startswith("#"):
            continue
        out.append(s)
    return out

rows = parse_requirements(req.read_text(encoding="utf-8"))
print("parsed", len(rows), "entries")
for r in rows:
    print("-", r)

List installed distributions via importlib.metadata

from importlib.metadata import distributions

names = sorted({d.metadata["Name"] for d in distributions() if d.metadata.get("Name")})
print("installed count:", len(names))
print("first 10:", ", ".join(names[:10]))

Simulate pip freeze style pins from metadata

from importlib.metadata import distributions

pins: list[str] = []
for d in distributions():
    name = d.metadata.get("Name")
    version = d.metadata.get("Version")
    if name and version:
        pins.append(f"{name}=={version}")
pins = sorted(pins, key=str.lower)
Path = __import__("pathlib").Path
out = Path("freeze_demo.txt")
out.write_text("\n".join(pins[:20]) + "\n", encoding="utf-8")
print(out.read_text(encoding="utf-8"))

Check whether a module is importable (dependency sanity)

import importlib.util

candidates = ["math", "json", "requests", "rich", "not_a_real_pkg_xyz"]
for name in candidates:
    spec = importlib.util.find_spec(name)
    print(f"{name:20} {'YES' if spec else 'NO'}")

Compare sys.prefix vs base_prefix (venv detection)

import sys

base = getattr(sys, "base_prefix", sys.prefix)
print("prefix     :", sys.prefix)
print("base_prefix:", base)
if sys.prefix == base:
    print("Status: system / base interpreter")
else:
    print("Status: virtual environment active")
L5

Problem Solving Tricks

  • Always python -m pip to target the intended interpreter.
  • Put .venv/ in .gitignore.
  • Create one venv per project directory.
  • Activation is optional if you call .venv/Scripts/python.exe explicitly.
  • Freeze after the app stabilizes; review the file before committing.
  • Keep runtime and dev requirements separate.
  • If imports fail, print sys.executable first.
  • Upgrade pip inside the venv before installing complex stacks.
  • Prefer wheels; read build errors as “wrong Python version / missing compiler”.
  • Document the minimum Python version next to your requirements.
L6

Practice Programs List

  1. Create a .venv, activate it, and install requests, then import requests successfully.
  2. Generate requirements.txt with pip freeze and recreate the env from scratch.
  3. Split deps into requirements.txt and requirements-dev.txt.
  4. Demonstrate installing with the wrong pip and show mismatched sys.executable.
  5. Write a short README section with Windows and Linux activate commands.
  6. Use pip show to find a package’s Location and Requires lines.
  7. Create a venv programmatically with venv.EnvBuilder and print pyvenv.cfg.
  8. Try pip install -e . on a tiny package with pyproject.toml.
  9. Parse a requirements file and validate that each line is either a comment or a requirement.
  10. Compare venv with a tool like uv or Poetry at a high level (notes only).
  11. Break and fix a version conflict between two pinned packages in a practice file.
  12. Detect whether code is running inside a venv using sys.prefix != sys.base_prefix.