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
Version history: any change can be undone, and collaboration is safe.
Pinned dependencies, so the code runs identically anywhere.
A systematic method for locating and fixing errors.
This session addresses the course's principle: code another person can run next year with the same result. These practices achieve it.
Track a change in Git and lock a project's dependencies.
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
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
A project folder that Git is tracking, together with its whole saved history.
e.g. a ds208-project/ folder after git init
One saved snapshot of the project, with a message saying what changed and why.
e.g. git commit -m "Fix region totals"
A separate line of commits for trying something without touching the working version.
e.g. a branch called feature/regional-breakdown
Bringing the commits from one branch into another, combining the two lines of work.
e.g. git merge feature/regional-breakdown while on main
A copy of the repository on another computer, usually a website like GitHub, that everyone shares.
e.g. github.com/you/ds208-project
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
A package the code needs in order to run.
e.g. an analysis that depends on pandas and matplotlib
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
The tool that downloads and installs packages. pip comes with Python; conda comes with Anaconda.
e.g. pip install pandas
A text file, requirements.txt, listing every package the project needs, one per line.
e.g. a line reading pandas==3.0.5
Recording the exact version to install, so everyone obtains the same one.
e.g. ==3.0.5 in pandas==3.0.5
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
A marked line where the program pauses and hands control to the debugger.
e.g. writing breakpoint() on the line before the crash
Running a paused program one line at a time, watching what each line does.
e.g. typing n (next line) at the (Pdb) prompt
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"
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.
Lost history, mismatched versions, bugs that cannot be retraced.
Track changes, pin dependencies, debug methodically.
Linus Torvalds begins Git after Linux loses free use of its old tool, BitKeeper.
Four days later, Git tracks its own code.
Released by Junio Hamano, who took over as maintainer in July.
A website for sharing Git projects launches in April.
Torvalds joked that he names projects after himself: “git” is British slang for an unpleasant person.
Git is the tool on your computer that records versions; GitHub is a website that stores copies of them online. They are different things.
SourceWikipedia: Git; Wikipedia: GitHub
of 71,379 developers in Stack Overflow’s 2022 survey use Git, up from 69.3% in 2015.
developers on GitHub in 2025.
Git still manages the Linux kernel, the job it was written for.
With version history, every change to an analysis can be checked, explained and undone.
SourceWikipedia: Git (citing the Stack Overflow 2022 survey); GitHub Octoverse 2025
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.
The git outputs on these slides were produced by running the same commands in a scratch repository.
pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browsert.dtypeseach column’s type: str on the laptop, object in the browserA 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.
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.
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.
Any past snapshot can be restored in seconds.
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.
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.pystage: include this file's current changes in the next commitgit commit -m "…"save everything staged as one commit; -m attaches the message in quotesgit pushupload the new commits to the remote so others can obtain themVersion control is most valuable when something breaks and the change responsible must be identified. These commands answer that question.
The default format shows four lines per commit. One line per commit allows fifty to be scanned at once.
git log --oneline -10the last 10 commits, one line each: short ID, then message6b80d5ea commit's ID (its SHA, a unique fingerprint); typing it refers to that commit-- path/to/fileonly the commits that touched that one filegit show 8e2216ewhat that one commit changedgit diffa diff is the line-by-line changes: here, edits not yet staged; --staged shows what the next commit will savegit blame file.pyfor each line, which commit (and person) last changed it| Command | What it undoes | History | Safe to use after pushing |
|---|---|---|---|
git restore <file> | Uncommitted edits to that file | Untouched | Yes — nothing was committed |
git revert <sha> | A commit, by adding an inverse commit | Preserved, moves forward | Yes — this is the shared-branch answer |
git reset --hard <sha> | Everything back to that commit | Rewritten | No — it breaks everyone else’s clone |
Guideline: revert in public, reset in private. Once a commit is pushed and someone has pulled it, rewriting it creates work for them; reverting it does not.
<file>, <sha>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.
In a scratch repo, after reset --hard HEAD~1 the discarded commit is the second line of git reflog.
HEAD~1HEAD is the current commit; ~1 means "one before it"git reset --hard …move back to that commit and throw away everything after itgit reflogGit's local record of every position of HEAD, newest firstHEAD@{1}: commit: secondone move ago HEAD was on commit 1992960, "second": the "lost" commitEach command moves a change one step to the right. add picks what to
save, commit saves it, push shares it. The working
directory is the project folder as it currently appears; the staging area is
the pile for the next commit.
Sending a parcel, where items go in the box (add), the box is sealed and labelled (commit), and it is handed to the courier (push); pull receives parcels from others.
git pull brings others' changes down before work begins.
One idea per commit, which is easy to review and to undo.
"Fix off-by-one in slice," not "stuff." The main reader is the author, later.
.gitignoreData, secrets, and .venv are never committed; listing them ignores them.
A committed API key or password is a leak: even after deletion, it remains in the history. Secrets are ignored from the first day. .gitignore is a plain text file in
the repo listing files and folders Git should never start tracking; a secret
is anything that grants access, such as a password or API key (week 9).
Keys go in environment variables and a .gitignore, never in a commit.
This is the most common security error in student repositories.
.gitignore tells git what not to start tracking; it has no effect on a file already in the index.
After .env is committed and then added to .gitignore, git ls-files still lists it.
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 workedgit 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)git rm --cached stops future commits from including it. The versions already committed are untouched, and anyone who cloned the repo has them.
After untracking, git log -p -- .env still printed the secret twice. History is append-only until it is rewritten.
git rm --cached .envstop tracking the file; --cached keeps it on diskgit 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 SECRET2the secret still appears twice in the saved historyThe key is compromised from the moment it was pushed. Revoke the key and issue a new one — this is the only step that definitely works.
git filter-repo (or BFG) rewrites every commit. It changes every SHA, so it requires coordination with anyone who has cloned the repository.
.env in .gitignore from the first commit, a committed .env.template with blank values, and a secret scanner in CI.
Step 1 always comes first. Rewriting history is slow and coordinated; rotation is immediate and complete. A cleaned repo with a live leaked key is still compromised.
1992960A 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.
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.
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 inA 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.
Not per day, not per person. One branch for "add the regional breakdown", merged when it works.
git switch -c feature/…create a new branch (-c) and move onto itgit switch mainreturn to main, the main line of workgit merge feature/…bring that branch's commits into the current branchgit branch -D feature/…delete the branch, and any work only it had| ✗ Useless | ✓ Useful |
|---|---|
update | fix region totals double-counted after merge |
fix bug | pin pandas to 3.0.5 — 2.x changes copy semantics |
changes | add duration column + assert it is non-negative |
asdf | drop rows with no budget (cannot answer spend question) |
The test: in six months, a scan of git log --oneline should locate the commit that introduced a behaviour. A message states what changed and why; the diff already shows how.
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.
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.
import pandas)pip (comes with Python) or conda (comes with Anaconda, and can install Python itself)One project's packages cannot clash with another's.
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.
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 .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 onlyconda create -n ds208 python=3.12 pandas then conda activate ds208. Same idea: one named environment per project.
"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.
Week 6 taught the pandas 3 copy rule because the version determines the result. An unpinned requirement is a moving target.
pandas==3.0.5== pins exactly version 3.0.5pip freeze > requirements.txtlist every installed package with its exact version, and write the list into requirements.txtuv 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 needInstalled globally, a package upgrade for one project silently changes another. A per-project environment makes that impossible.
.venv/ goes in .gitignore. The recipe (requirements) is committed, not the result, which is large and platform-specific.
uv venvequivalent to python -m venv .venv, but fasteruv 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| Check | Why |
|---|---|
| Runs after Restart & Run All | Proves it does not depend on state from deleted cells |
Pinned requirements.txt | pandas 2 vs 3 changes behaviour, not only speed |
| Relative paths only | An absolute path is the commonest reason a classmate cannot run it |
| No data or secrets committed | Both live in history forever once pushed |
| README: what, how to run, where the data comes from | Three short sections, written on day one |
| Asserts on the invariants that matter | Row counts and impossible values; a failing run is preferable to a wrong number |
Every item caused a problem in a previous week of this course. The checklist is run on a fresh clone in a fresh environment; only this test demonstrates reproducibility.
data/flood.csv, measured from the project folder; not C:\Users\ana\…| Cause | How to detect it | Fix |
|---|---|---|
| Different package version | pip freeze | grep pandas on both machines | Pin it; share the lock file |
| Different Python version | python --version | State it in the README; pin in the project config |
| A file only the author has | Others get FileNotFoundError | Relative paths via pathlib; document how to get the data |
| Hidden notebook state | Works for the author, fails on a fresh kernel | Restart & Run All before sharing, every time. |
The last one is the most common and the least suspected. A notebook accumulates variables from cells since edited or deleted, so it can depend on code that no longer exists.
pip freeze | grep pandas| feeds the package list to grep, which keeps only lines containing "pandas"pathlibrequirements.txt pins the versionsfreeze 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.txtwrite the exact installed versions into the requirements file; commit that filepip install -r requirements.txton another computer, inside a fresh environment: install exactly that listconda env export > environment.ymlthe conda version of the same recipe; rebuilt with conda env create -f environment.ymlWhich command saves a snapshot of the staged changes to the local history?
git addgit commitgit pushgit pullB — git commit.
add stages what to save,
commit saves the snapshot locally, and push shares it to the
remote. Three distinct steps.
add → stage, commit → save, push → share: three distinct operations.
commit writes to history; push shares it.
Next: systematic 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 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 populationThe 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.
cities["popn"]a typo: the column is called popKeyError: 'popn'read the LAST line first: the error type, then the value that caused itthe lines above itwhere it happened: the top frame is your code, the rest is inside pandasA 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.
Most bugs involve a value that differs from the assumed one. A print checks it; breakpoint() pauses execution for live inspection.
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, columnsdf.columns.tolist()the real column names as a plain list: compare the spelling with the typed namebreakpoint()pause here and open the debugger, a tool for looking inside a paused programThe error is triggered again deliberately, with the smallest input that causes it. A reproducible bug is solvable.
Half the code is commented out, narrowing the search to the exact faulty line.
The value assumed to be correct is printed; it is often the wrong one.
When progress stops, explaining the problem aloud line by line (the "rubber duck" method) often reveals the flaw.
Search for the exact error message; others have usually encountered it.
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.
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.
(Pdb)the debugger's prompt: a one-letter command followed by Enterp df.shapeprint any value, as it is right nown vs srun the next line; or step into the function that line callsc, qcarry on to the next breakpoint; or stop the programWhen a 60-line pipeline produces a wrong answer, the middle is checked first and half is discarded, rather than reading all 60.
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.
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.
… ; print(len(df)); puts two statements on one line: run the step, then print the row count34079after load, clean and derive: still one row per project, as expected68158 <-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)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.
df["duration"] = …days from start to completion; NaN where a date is missing(34079, 16)34,079 projects; 15 columns plus durationThe costliest bugs are silent and surface far from their origin. An assertion (assert) converts a silent wrong answer into an explicit stop.
"the row count did not change" and "durations are not negative" — the properties that must hold if the step worked.
regions = df[["region"]].drop_duplicates()a lookup table with one row per region, so the merge cannot add rowsassert len(df) == before, …passes: the merge kept all 34,079 rowsassert df.duration.min() >= 0, …fails: one project is recorded as finishing 17 days before it started (week 6)Debug prints get deleted, then re-added next time the bug appears. Logging allows the same lines to remain and be silenced.
INFO is the normal level; DEBUG is used when something breaks. No edits, no re-adding prints.
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.
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 filelog.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 moreA minimal reproducible example (MRE) is the shortest piece of code, with the smallest data, that still shows the bug.
Everything the error does not need is deleted. Most bugs become obvious at about line five.
Three hand-written rows instead of 34,079. If it still fails, the data was never the problem.
The result is code another person can run in ten seconds, which makes a question far more likely to be answered.
The main benefit: the bug is usually found during the reduction. Every piece removed is a hypothesis tested. The MRE is debugging, and being able to ask a good question is the by-product.
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.
git rm --cached, commit, then git log -p. Find the fake key still there.
reset --hard HEAD~1, then recover it from git reflog.
Add a row-count assert around a merge. Make it fail deliberately, and read where it stops.
Step 1 is the essential one to run: observing that .gitignore does not untrack a committed file is more instructive than reading about it.
A .env file with a live API key was committed, then .env was added to .gitignore and pushed. What is the situation?
git rm --cached .env is run.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.A notebook runs correctly for its author and fails on a classmate’s machine at cell 3. What should be checked first?
.venv folderThe error named a missing column. Printing the real column names showed the typo. Read, check, fix, without guessing.
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).
KeyError: 'popn'last line first: no column called popndf.columnscheck the assumption: the real names are city, region, popdf["pop"]with the real name, the error disappearsWhen reading a traceback, which line usually names the actual error?
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.
Tracebacks are read bottom-up; the last line is the summary.
Error type + message = last line.
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.
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.
Write a .gitignore that excludes data/ and .venv/.
add → commit → push; small commits, clear messages, ignored secrets.
venv to isolate; requirements.txt to pin versions.
Reading the traceback; reproducing, isolating, checking assumptions.
In summary: recorded history, pinned dependencies, and methodical debugging make work run identically for everyone.
Hand a project to another person and have it run without changes.
git and pipgit add)6b80d5eHEAD~1 is the one beforerequirements.txt: the packages a project needs, one per linepandas==3.0.5pdb)breakpoint()n, s)assert: stop with an error if a condition is FalseComplete and submit the Week 11 lab. Place the integrative project under Git from the first commit.
GitHub's "Git Handbook" — docs.github.com/en/get-started/using-git.
All materials are linked on the course page beside this deck.
The integrative project: every skill in this course, applied to one dataset.
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