DS 208 · Week 11

Reproducible Workflows

Code that another person can run next year with the same result, using Git for history, environments for dependencies, and systematic debugging.

Programming for Data Science · University of the Philippines Cebu

Outline

Three practices of professional work

Key terms · 1 of 2

Eight terms for version history

reproducibility

Another person can rerun the work, on their own computer, and obtain the same result.

e.g. a classmate runs the notebook next year and obtains the same total

version control

A system that saves named snapshots of files so that any of them can be restored, compared or shared. This course uses Git.

e.g. the code as it was last Tuesday

repository (repo)

A project folder that Git is tracking, together with its whole saved history.

e.g. a ds208-project/ folder after git init

commit

One saved snapshot of the project, with a message saying what changed and why.

e.g. git commit -m "Fix region totals"

branch

A separate line of commits for trying something without touching the working version.

e.g. a branch called feature/regional-breakdown

merge

Bringing the commits from one branch into another, combining the two lines of work.

e.g. git merge feature/regional-breakdown while on main

remote

A copy of the repository on another computer, usually a website like GitHub, that everyone shares.

e.g. github.com/you/ds208-project

push / pull

Push sends new commits up to the remote; pull brings other people's commits down.

e.g. git push after committing; git pull before starting

Key terms · 2 of 2

Nine terms for environments and debugging

dependency

A package the code needs in order to run.

e.g. an analysis that depends on pandas and matplotlib

environment

The Python plus the exact set of installed packages that the code runs with. A virtual environment is a private one per project.

e.g. a .venv folder inside the project

package manager (pip / conda)

The tool that downloads and installs packages. pip comes with Python; conda comes with Anaconda.

e.g. pip install pandas

requirements file

A text file, requirements.txt, listing every package the project needs, one per line.

e.g. a line reading pandas==3.0.5

version pin

Recording the exact version to install, so everyone obtains the same one.

e.g. ==3.0.5 in pandas==3.0.5

debugger

A tool that pauses a running program so that every variable can be inspected and execution advanced line by line.

e.g. Python's built-in pdb

breakpoint

A marked line where the program pauses and hands control to the debugger.

e.g. writing breakpoint() on the line before the crash

stepping

Running a paused program one line at a time, watching what each line does.

e.g. typing n (next line) at the (Pdb) prompt

assertion

A line that checks something must be true and stops the program with an error if it is not.

e.g. assert len(df) > 0, "no rows loaded"

Previous session

Working on one machine is insufficient

Weeks 5–10 covered loading, analysing, and plotting. Work that runs only on its author’s laptop is not yet science. Reproducibility (anyone can rerun it and get the same result) is what makes work trustworthy.

A good recipe lists exact amounts and steps so anyone can bake the same cake; a reproducible analysis is written in the same way.

Risks

Lost history, mismatched versions, bugs that cannot be retraced.

Remedies

Track changes, pin dependencies, debug methodically.

About the tool

Git was written in 2005 to manage Linux

3 Apr 2005

Started

Linus Torvalds begins Git after Linux loses free use of its old tool, BitKeeper.

7 Apr 2005

Self-hosting

Four days later, Git tracks its own code.

Dec 2005

Git 1.0

Released by Junio Hamano, who took over as maintainer in July.

2008

GitHub

A website for sharing Git projects launches in April.

SourceWikipedia: Git; Wikipedia: GitHub

About the tool

How widely Git is used

SourceWikipedia: Git (citing the Stack Overflow 2022 survey); GitHub Octoverse 2025

Runnable code

Which blocks run this week

Git and environment commands are typed in a terminal, not in Python, so those blocks have no Run button: try them in a terminal on your own machine. The debugging examples in Part C are Python, and run in the browser as in earlier weeks.

Checked, not invented

The git outputs on these slides were produced by running the same commands in a scratch repository.

import io, sys print("pandas version:", pd.__version__) print("64-bit Python:", sys.maxsize > 2**32) t = pd.read_csv(io.StringIO("city,pop\nCebu,964000")) print(t.dtypes) pandas version: 3.0.5 64-bit Python: True city str pop int64 dtype: object
  • pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browser
  • t.dtypeseach column’s type: str on the laptop, object in the browser
Part A

Git

A system of save points for code.

Saving files is familiar. This part adds version control: saving named snapshots that can be restored, compared, and shared with others.

Motivation

Every change can be undone and explained

Git records snapshots of a project over time. Changes can be undone, the author and reason for each change can be seen, and work from several people can be merged without conflict.

A folder Git tracks is a repository (repo); each saved snapshot is a commit.

Where git commands are run

Into a terminal (the command line): a text window for typing instructions to the computer. Terminal on macOS/Linux, PowerShell or Git Bash on Windows. Not into Python or a notebook cell. They are run from inside the project folder.

History

Any past snapshot can be restored in seconds.

Teamwork

Many people work on one project without overwriting each other.

Git resembles version history in Google Docs, except that the user decides when a version is saved and writes a note on each one explaining why.

Routine workflow

The add, commit, push cycle

Changed files are staged, a snapshot is saved with a message, and it is sent to the shared copy. These three commands are run many times a day.

To stage a file is to put its changes in the "next snapshot" pile; to push is to upload commits to the remote, the shared copy (e.g. on GitHub).

git add analysis.py git commit -m "Add city density calc" git push
  • git add analysis.pystage: include this file's current changes in the next commit
  • git commit -m "…"save everything staged as one commit; -m attaches the message in quotes
  • git pushupload the new commits to the remote so others can obtain them
Reading history

Four commands for inspecting history

Version control is most valuable when something breaks and the change responsible must be identified. These commands answer that question.

--oneline makes log usable

The default format shows four lines per commit. One line per commit allows fifty to be scanned at once.

git log --oneline -10 6b80d5e expand week 10 decks 8e2216e expand week 9 decks 625da22 expand week 8 decks git log --oneline -- path/to/file # one file git show 8e2216e # one commit git diff # unstaged now git diff --staged # what commit will take git blame file.py # who + when, per line
  • git log --oneline -10the last 10 commits, one line each: short ID, then message
  • 6b80d5ea commit's ID (its SHA, a unique fingerprint); typing it refers to that commit
  • -- path/to/fileonly the commits that touched that one file
  • git show 8e2216ewhat that one commit changed
  • git diffa diff is the line-by-line changes: here, edits not yet staged; --staged shows what the next commit will save
  • git blame file.pyfor each line, which commit (and person) last changed it
Three undo commands

Choosing an undo command by what must be kept

CommandWhat it undoesHistorySafe to use after pushing
git restore <file>Uncommitted edits to that fileUntouchedYes — nothing was committed
git revert <sha>A commit, by adding an inverse commitPreserved, moves forwardYes — this is the shared-branch answer
git reset --hard <sha>Everything back to that commitRewrittenNo — it breaks everyone else’s clone
reset is recoverable

reflog records commits that log no longer shows

After a hard reset the commit appears to be gone, as it is no longer in git log. However, git keeps the pointer for weeks.

Verified in a test repository

In a scratch repo, after reset --hard HEAD~1 the discarded commit is the second line of git reflog.

git reset --hard HEAD~1 # "second" is gone from git log git reflog 080d423 HEAD@{0}: reset: moving to HEAD~1 1992960 HEAD@{1}: commit: second # get it back git reset --hard 1992960 # reflog is LOCAL and expires (~90d). # it saves you from yourself, not from # a lost laptop
  • HEAD~1HEAD is the current commit; ~1 means "one before it"
  • git reset --hard …move back to that commit and throw away everything after it
  • git reflogGit's local record of every position of HEAD, newest first
  • HEAD@{1}: commit: secondone move ago HEAD was on commit 1992960, "second": the "lost" commit
Conceptual model

The four locations of a change

working dirlocal edits stagingready to save local repocommit history remoteshared git add git commit git push
Guidelines

Small commits, clear messages, ignored secrets

A committed API key

Adding a committed file to .gitignore has no effect

This is the most common security error in student repositories.

.gitignore affects only untracked files

Once committed, a file stays tracked

.gitignore tells git what not to start tracking; it has no effect on a file already in the index.

Verified in a real repository

After .env is committed and then added to .gitignore, git ls-files still lists it.

echo "SECRET=abc123" > .env git add .env && git commit -m "oops" echo ".env" > .gitignore git add .gitignore && git commit -m "ignore it" git ls-files .env <- STILL TRACKED .gitignore
  • echo "SECRET=abc123" > .envcreate a file .env containing that line (> writes a command's output into a file)
  • &&run the second command only if the first one worked
  • git ls-fileslist every file Git is tracking (watching for changes)
  • .env <- STILL TRACKED.gitignore came too late: the file was already in the index (the staging area)
Untracking is not erasing

The secret remains in every clone

git rm --cached stops future commits from including it. The versions already committed are untouched, and anyone who cloned the repo has them.

Measured in the scratch repo

After untracking, git log -p -- .env still printed the secret twice. History is append-only until it is rewritten.

git rm --cached .env git commit -m "untrack" git ls-files .gitignore # good, not tracked now git log --all -p -- .env | grep -c SECRET 2 # STILL IN HISTORY
  • git rm --cached .envstop tracking the file; --cached keeps it on disk
  • git log --all -p -- .envevery past version of .env, with its contents (-p)
  • | grep -c SECRET| feeds that output to grep, which counts the lines containing SECRET
  • 2the secret still appears twice in the saved history
Remediation

Three remediation steps, the first outside git

Ignoring data

Data files also belong in .gitignore

A committed dataset permanently enlarges every clone, and if it contains personal data, it is in the history under the same rules as a leaked key.

The week-11 connection

DS 227 (the companion course) has covered why deletion is difficult. Version control is one of the places a “deleted” file lives on: every old commit still holds it.

# a starting .gitignore .env .env.local data/ *.csv *.parquet __pycache__/ .venv/ .ipynb_checkpoints/ .DS_Store # commit .env.template instead — # same keys, empty values
  • data/a trailing / means a whole folder
  • *.csv* is a wildcard: any file name ending in .csv
  • __pycache__/, .ipynb_checkpoints/folders Python and Jupyter create by themselves
  • .env.templatethe same setting names with blank values: safe to share, and shows others what to fill in
Branches

Branches for experiments that leave working code intact

A branch is a movable label on a commit. Creating one costs nothing and allows an experiment to be abandoned without undoing it. To merge is to bring a branch's commits into another branch.

A branch is a draft copy for trying an idea; if it works, merging returns the changes to the main version, and otherwise the draft is deleted.

One branch per piece of work

Not per day, not per person. One branch for "add the regional breakdown", merged when it works.

git switch -c feature/regional-breakdown # ...commit as usual... git switch main git merge feature/regional-breakdown # or throw it away, cost-free git switch main git branch -D feature/regional-breakdown git branch # list them git switch - # previous branch
  • git switch -c feature/…create a new branch (-c) and move onto it
  • git switch mainreturn to main, the main line of work
  • git merge feature/…bring that branch's commits into the current branch
  • git branch -D feature/…delete the branch, and any work only it had
Commit messages

Commit messages as documentation that does not go out of date

✗ Useless✓ Useful
updatefix region totals double-counted after merge
fix bugpin pandas to 3.0.5 — 2.x changes copy semantics
changesadd duration column + assert it is non-negative
asdfdrop rows with no budget (cannot answer spend question)
Part B

Environments

Pinned installations that run identically anywhere.

Part A covered keeping code history. This part ensures that the tools the code needs (pandas, NumPy, …) are the same versions on every computer that runs it.

Motivation

Different versions, different results

Code written with pandas 2.2 fails on a classmate’s pandas 1.5. A virtual environment gives each project its own isolated set of packages, at known versions.

New words

package
an installable library, like pandas (week 5: import pandas)
dependency
a package the code needs in order to run
package manager
the installer: pip (comes with Python) or conda (comes with Anaconda, and can install Python itself)

Isolated

One project's packages cannot clash with another's.

Recorded

Exact versions are recorded, so anyone can rebuild the same setup.

An environment is a separate toolbox for each project, so replacing a tool in one box does not affect another.

Create and activate

A new environment for each project

A .venv folder is created and activated, then packages are installed. After activation, every pip install affects this project only; nothing global is changed.

python -m venv .venv source .venv/bin/activate pip install pandas matplotlib
  • python -m venv .venvcreate a new, empty environment in a folder called .venv (-m venv = run Python's built-in venv tool)
  • source .venv/bin/activateactivate: make this terminal use that environment (Windows: .venv\Scripts\activate)
  • pip install pandas matplotlibdownload and install both packages into .venv only

Conda equivalent (Anaconda users)

conda create -n ds208 python=3.12 pandas then conda activate ds208. Same idea: one named environment per project.

Pinning versions

requirements.txt without versions is not reproducible

"pandas" means whatever pandas exists the day someone installs. Between pandas 2 and 3, Copy-on-Write (the week 6 copy rule) became permanent — the same code, different behaviour. A version pin fixes the exact version.

Version-dependent behaviour

Week 6 taught the pandas 3 copy rule because the version determines the result. An unpinned requirement is a moving target.

# not reproducible pandas numpy matplotlib # reproducible pandas==3.0.5 numpy==2.5.3 matplotlib==3.11.2 pip freeze > requirements.txt # or, better, a lock file: uv pip compile requirements.in -o requirements.txt
  • pandas==3.0.5== pins exactly version 3.0.5
  • pip freeze > requirements.txtlist every installed package with its exact version, and write the list into requirements.txt
  • uv pip compile …uv is a newer, faster package manager: it turns a short wish-list (requirements.in) into a lock file that pins every package, including those the listed packages need
One environment per project

Isolating projects from each other

Installed globally, a package upgrade for one project silently changes another. A per-project environment makes that impossible.

The environment is not committed

.venv/ goes in .gitignore. The recipe (requirements) is committed, not the result, which is large and platform-specific.

uv venv # create source .venv/bin/activate # mac/linux .venv\Scripts\activate # windows uv pip install -r requirements.txt # confirm you are where you think which python /path/to/project/.venv/bin/python # wrong answer = you are installing # into the system python
  • uv venvequivalent to python -m venv .venv, but faster
  • uv pip install -r requirements.txtinstall exactly what the file lists (-r = read the list from this file)
  • which pythonwhich Python this terminal will run (Windows: where python). It should be inside the project's .venv
Reproducibility checklist

What "done" means for the final project

CheckWhy
Runs after Restart & Run AllProves it does not depend on state from deleted cells
Pinned requirements.txtpandas 2 vs 3 changes behaviour, not only speed
Relative paths onlyAn absolute path is the commonest reason a classmate cannot run it
No data or secrets committedBoth live in history forever once pushed
README: what, how to run, where the data comes fromThree short sections, written on day one
Asserts on the invariants that matterRow counts and impossible values; a failing run is preferable to a wrong number
"It works on my machine"

Four causes, in order of checking

CauseHow to detect itFix
Different package versionpip freeze | grep pandas on both machinesPin it; share the lock file
Different Python versionpython --versionState it in the README; pin in the project config
A file only the author hasOthers get FileNotFoundErrorRelative paths via pathlib; document how to get the data
Hidden notebook stateWorks for the author, fails on a fresh kernelRestart & Run All before sharing, every time.
Requirements file

requirements.txt pins the versions

freeze writes every package and its exact version to a file. Once it is committed, anyone can rebuild the environment with one command.

pip freeze > requirements.txt # on any other machine: pip install -r requirements.txt
  • pip freeze > requirements.txtwrite the exact installed versions into the requirements file; commit that file
  • pip install -r requirements.txton another computer, inside a fresh environment: install exactly that list
  • conda env export > environment.ymlthe conda version of the same recipe; rebuilt with conda env create -f environment.yml
Review question

Question (select to reveal the answer)

Which command saves a snapshot of the staged changes to the local history?

A · git add
B · git commit
C · git push
D · git pull

B — git commit.

add stages what to save, commit saves the snapshot locally, and push shares it to the remote. Three distinct steps.

Break

  Five minutes

Next: systematic debugging.

Part C

Debugging

A systematic approach to errors.

Error messages have appeared throughout the course. This part makes fixing them a routine: read the error, reproduce it, narrow it down, and check assumptions.

The small table

Week 7’s eight cities, again

The debugging examples break and fix code on the eight-city table from week 7, so every error is small enough to see whole.

  • citieseight cities: name, island group (region) and approximate 2020 population
import io csv_text = """city,region,pop Quezon City,Luzon,2960000 Manila,Luzon,1847000 Baguio,Luzon,366000 Cebu,Visayas,964000 Iloilo,Visayas,457000 Tacloban,Visayas,251000 Davao,Mindanao,1777000 Cagayan de Oro,Mindanao,728000""" cities = pd.read_csv(io.StringIO(csv_text)) areas = pd.DataFrame({ "city": ["Quezon City", "Manila", "Baguio", "Cebu", "Iloilo", "Tacloban", "Davao", "Cagayan de Oro"], "area_km2": [172, 42, 58, 315, 78, 202, 2444, 413]}) print(cities.shape, areas.shape) (8, 3) (8, 2)
Reading errors

The traceback states where and what

The last line names the error type and message; the lines above show the path to it. It is read bottom-up; the answer is usually stated there in plain English.

A traceback is the report Python prints when a program stops with an error (an exception); a bug is the mistake in the code that caused it.

# fails on purpose: read the last line # cities: the eight-city table print(cities["popn"].mean()) # a typo in the column name KeyError: 'popn'
  • cities["popn"]a typo: the column is called pop
  • KeyError: 'popn'read the LAST line first: the error type, then the value that caused it
  • the lines above itwhere it happened: the top frame is your code, the rest is inside pandas

A full traceback starts with Traceback (most recent call last): and can list many lines inside pandas' own files. Those are skipped in favour of the lines that name the user’s file.

Inspecting values

Printing values and pausing to inspect

Most bugs involve a value that differs from the assumed one. A print checks it; breakpoint() pauses execution for live inspection.

# cities: the eight-city table print(f"shape: {cities.shape}") print(cities.columns.tolist()) # breakpoint() here would pause and let you look (next slide) shape: (8, 3) ['city', 'region', 'pop']
  • print(f"shape: {df.shape}")an f-string fills in the value inside { }: for the flood data it prints shape: (34079, 15), i.e. rows, columns
  • df.columns.tolist()the real column names as a plain list: compare the spelling with the typed name
  • breakpoint()pause here and open the debugger, a tool for looking inside a paused program
Debugging method

Reproduce, isolate, check

breakpoint()

Pausing execution to inspect state

A print shows one value chosen in advance. A breakpoint allows any value to be inspected at that moment, including questions that arise only during inspection.

Built in since Python 3.7

No import is needed. breakpoint() is placed on the line before the failure and the program is run normally.

A breakpoint is, by analogy, a pause button on a film: the frame freezes and everything in it can be examined. Stepping is advancing one frame at a time.

def clean(df): breakpoint() # execution stops here return df.dropna() # at the (Pdb) prompt: p df.shape print an expression n next line s step into a call c continue l list code around here q quit
  • (Pdb)the debugger's prompt: a one-letter command followed by Enter
  • p df.shapeprint any value, as it is right now
  • n vs srun the next line; or step into the function that line calls
  • c, qcarry on to the next breakpoint; or stop the program
Exercise · 3 min

Halving the suspect region to a single line

When a 60-line pipeline produces a wrong answer, the middle is checked first and half is discarded, rather than reading all 60.

Six checks for sixty lines

Each check halves the remainder. This is the same method as guessing a number from 1 to 100 by always asking “higher or lower?” (called binary search), applied to code.

Tasks

  1. Predict after which step the row count changes.
  2. Select ▶ Run / Edit and run the code.
  3. Fix it: in merge_regions, merge with regions.drop_duplicates(). What is the last count now?

Result on the lecture laptop (select to reveal)

8, 8, 8, then 11 after merge_regions: Luzon is listed twice in regions, so each of the three Luzon cities is doubled. With regions.drop_duplicates() the count stays 8: the counter pointed at the one function worth reading.

# cities: the eight-city table regions = pd.DataFrame({"region": ["Luzon", "Luzon", "Visayas", "Mindanao"], "island": ["Luzon", "Luzon", "Visayas", "Mindanao"]}) def load(): return cities.copy() def clean(d): return d.dropna() def derive(d): return d.assign(pop_k=d["pop"] / 1000) def merge_regions(d): return d.merge(regions, on="region", how="left") df = load(); print(len(df)) df = clean(df); print(len(df)) df = derive(df); print(len(df)) df = merge_regions(df); print(len(df))
  • … ; print(len(df)); puts two statements on one line: run the step, then print the row count
  • 34079after load, clean and derive: still one row per project, as expected
  • 68158 <-exactly double: the merge matched every row twice, because the region table listed each region twice (a duplicated join key, the column that matches rows, week 7)
Case study

The flood data, for the assert example

The next slide checks two assumptions on the real flood data: that a merge keeps every row, and that no project finishes before it starts. It uses week 6’s duration.

The browser cannot download the data, so this block has no Run button; the companion notebook runs it.

import io, requests url = "https://portal.latarak.com/api/flood/export.csv" df = pd.read_csv(io.StringIO(requests.get(url, timeout=60).text)) for col in ["start_date", "completion_date"]: df[col] = pd.to_datetime(df[col], errors="coerce") df["duration"] = (df.completion_date - df.start_date).dt.days print(df.shape) (34079, 16)
  • df["duration"] = …days from start to completion; NaN where a date is missing
  • (34079, 16)34,079 projects; 15 columns plus duration
assert at each assumption

Failing at the cause rather than three steps later

The costliest bugs are silent and surface far from their origin. An assertion (assert) converts a silent wrong answer into an explicit stop.

Asserting invariants, not values

"the row count did not change" and "durations are not negative" — the properties that must hold if the step worked.

# fails on purpose: read the last line regions = df[["region"]].drop_duplicates() # one row per region before = len(df) df = df.merge(regions, on="region", how="left") assert len(df) == before, f"row count changed: {before} -> {len(df)}" assert df.duration.min() >= 0, "negative duration" AssertionError: negative duration
  • regions = df[["region"]].drop_duplicates()a lookup table with one row per region, so the merge cannot add rows
  • assert len(df) == before, …passes: the merge kept all 34,079 rows
  • assert df.duration.min() >= 0, …fails: one project is recorded as finishing 17 days before it started (week 6)
Exercise · 3 min

Log levels silence messages without deleting them

Debug prints get deleted, then re-added next time the bug appears. Logging allows the same lines to remain and be silenced.

Purpose of levels

INFO is the normal level; DEBUG is used when something breaks. No edits, no re-adding prints.

Tasks

  1. Predict which of the three messages print.
  2. Select ▶ Run / Edit and run the code.
  3. Change level=logging.INFO to level=logging.WARNING. Which messages remain?

Result on the lecture laptop (select to reveal)

The INFO and WARNING lines print; DEBUG is below the INFO level, so it is silent. At WARNING only WARNING 8 cities have no area yet remains: the other lines are still in the code, just silenced.

# cities: the eight-city table import logging, sys logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(levelname)s %(message)s", force=True) log = logging.getLogger("cities") log.debug("columns: %s", cities.columns.tolist()) log.info("loaded %s cities", len(cities)) log.warning("%s cities have no area yet", len(cities))
  • logging.basicConfig(level=…INFO, …)show messages of level INFO and above, formatted as "LEVEL message"
  • log = logging.getLogger(__name__)make a logger named after this file
  • log.debug(…) / log.info(…)at level INFO the debug line is hidden; the info line prints INFO loaded 34079 projects (%s is filled with len(df))
  • log.warning(…)with n = 12 it prints WARNING 12 rows had no budget. Levels run DEBUG < INFO < WARNING < ERROR; a lower level shows more
Minimal reproducible example

Reducing the code usually reveals the bug

A minimal reproducible example (MRE) is the shortest piece of code, with the smallest data, that still shows the bug.

Exercise · 8 min

Committing a secret and recovering

1 · Commit a "secret"

In a terminal, make a repo (mkdir demo, cd demo, git init), commit a file with a fake key. Add it to .gitignore. Confirm with git ls-files that it is still tracked.

2 · Untrack and check history

git rm --cached, commit, then git log -p. Find the fake key still there.

3 · Lose a commit and get it back

reset --hard HEAD~1, then recover it from git reflog.

4 · Assert the pipeline

Add a row-count assert around a merge. Make it fail deliberately, and read where it stops.

Review question

Question (select to reveal the answer)

A .env file with a live API key was committed, then .env was added to .gitignore and pushed. What is the situation?

A · Fixed — .gitignore stops it being tracked
B · The key is still tracked and still in history; rotate it first, then clean the history
C · Fixed once git rm --cached .env is run
D · Only a problem if the repository is public
B. .gitignore has no effect on an already-tracked file — git ls-files still lists it. git rm --cached (C) stops future commits but leaves every past version in history. Rotating the key is the only step that definitely works, and it comes first; history rewriting is slow and needs coordination. D is wrong: private repos get cloned, forked and backed up too.
Review question

Question (select to reveal the answer)

A notebook runs correctly for its author and fails on a classmate’s machine at cell 3. What should be checked first?

A · Their internet connection
B · Whether it still works for the author after Restart & Run All
C · Reinstall their Python
D · Send the classmate the .venv folder
B. A notebook keeps state from cells since edited or deleted, so it can depend on code that no longer exists in the file. Restart & Run All is the first check because it is the most common cause and takes ten seconds. D is never right — environments are large and platform-specific; share the pinned requirements instead.
Exercise · 3 min

Resolving a KeyError in three lines

The error named a missing column. Printing the real column names showed the typo. Read, check, fix, without guessing.

Tasks

  1. Predict the error message.
  2. Select ▶ Run / Edit and run the code.
  3. Change the fixed line to the median. What is the median population?

Result on the lecture laptop (select to reveal)

KeyError: 'popn'; the real names are ['city', 'region', 'pop'], and the mean population is 1,168,750. The median is 846,000, halfway between Cebu (964,000) and Cagayan de Oro (728,000).

# cities: the eight-city table try: print(cities["popn"].mean()) except KeyError as e: print("KeyError:", e) print(cities.columns.tolist()) # read the real names print(cities["pop"].mean()) # fixed
  • KeyError: 'popn'last line first: no column called popn
  • df.columnscheck the assumption: the real names are city, region, pop
  • df["pop"]with the real name, the error disappears
Review question

Question (select to reveal the answer)

When reading a traceback, which line usually names the actual error?

A · the very first line
B · the last line
C · the middle line
D · it varies randomly

B — the last line.

The bottom line gives the error type and message; the lines above trace the path to it. It is read bottom-up: what, then where.

This week's lab

Versioning, pinning and debugging

The browser lab covers reading tracebacks and fixing planted bugs, naming error types, guarding code with assert, and recording the exact package versions the code ran with. The Git and environment steps run in a local terminal (the Exercise activity). ~45 minutes.

Lab tasks

Reading tracebacks, try/except (week 4), assert, and __version__ (e.g. pd.__version__ gives '2.2.0', the installed version); plus git add/commit/push, venv and pip freeze in a terminal.

Optional extension

Write a .gitignore that excludes data/ and .venv/.

Summary

Tracking, pinning and debugging

Glossary · 1 of 2

Git terms, one line each

Key terms

reproducibility
anyone can rerun the work and get the same result
version control
saving named snapshots of files to return to or share (Git)
repository (repo)
a folder Git tracks, plus its whole history
commit
one saved snapshot, with a message saying why
branch
a separate line of commits for trying something safely
merge
bringing one branch's commits into another
remote
the shared copy of the repo, e.g. on GitHub
push / pull
upload one's commits / download other people's

Additional terms

terminal
text window for typing commands such as git and pip
stage
put changes in the pile for the next commit (git add)
working directory
the project folder in its current state
SHA
a commit's ID, like 6b80d5e
diff
the line-by-line changes between two versions
HEAD
the current commit; HEAD~1 is the one before
revert / reset
undo by adding a new commit / by moving back and discarding
reflog
local diary of every commit HEAD has pointed to
.gitignore
list of files Git should never start tracking
clone
a full copy of a repo, history included
Glossary · 2 of 2

Environment and debugging terms, one line each

Key terms

dependency
a package the code needs in order to run
environment
Python plus the exact installed packages; virtual = one per project
package manager (pip / conda)
the tool that installs packages
requirements file
requirements.txt: the packages a project needs, one per line
version pin
the exact version to install: pandas==3.0.5
debugger
tool that pauses a program for inspection (pdb)
breakpoint
the line where the program pauses: breakpoint()
stepping
running a paused program one line at a time (n, s)
assertion
assert: stop with an error if a condition is False

Additional terms

package
an installable library, such as pandas
lock file
pins every package, including the packages those packages need
activate
make the terminal use a given environment
traceback
Python's error report: read the last line first, then the line number
bug
the mistake in the code that causes a wrong result or error
invariant
a fact that must always hold, e.g. row count unchanged
logging
messages with levels that can be turned up or down
kernel
the running Python behind a notebook
minimal reproducible example
shortest code and data that still shows the bug
Preparation for next week

Practice & the project

Next Week

Integrative project & presentations

One dataset and the whole toolkit: loading, cleaning, analysing and visualising it, then presenting the findings to the class.

DS 208 · Programming for Data Science