Lecture 02: Dev Environment and Git

On this page

Gap lecture G2. Day 1 afternoon, after Lecture 01. Every later workshop and the capstone are delivered as GitHub repositories, so this session sets up the habits they rely on.

Recall

From this morning's Lecture 01, 10 minutes on paper. Solutions in exercises.md (R.1 to R.3).

  1. Predict the shape of np.ones((5, 1)) + np.ones((1, 3)), and say why X - X.mean(axis=1) fails for X of shape (100, 5).
  2. On a default integer index, how many rows do df.loc[0:2] and df.iloc[0:2] return?
  3. Write the normal equations for least squares, and say why we solve them with np.linalg.lstsq instead of an explicit inverse.

1. Isolated environments

Theory

A Python project depends on exact library versions. Phase 1 uses scikit-learn, Phase 2 TensorFlow, Phase 4 PyTorch and LangChain. Installed globally, these conflict: upgrading one project's library breaks another. A virtual environment gives each project its own interpreter and packages, and a requirements.txt lets anyone rebuild it.

Definitions

Definition (virtual environment). A directory holding a Python interpreter link and its own site-packages. While it is active, python and pip resolve to that directory first through PATH.

Plain English: a private copy of Python for one project. Packages installed while it is active go only there.

Definition (requirements file). A text file of package specifiers, one per line, such as numpy>=1.26. pip install -r requirements.txt installs all of them.

Symbols: >= is a minimum version, == pins an exact version, ~=1.4.2 is a compatible release: at least 1.4.2 and below 1.5.

Worked example: a project environment

Terminal
python -m venv .venv
Terminal
source .venv/bin/activate        # Windows: .venv\Scripts\activate
Terminal
which python                     # .../ds1-portfolio/.venv/bin/python
pip install -r requirements.txt
pip freeze > requirements.lock   # exact versions that work today

Steps:

  1. python -m venv .venv creates the folder. It is named with a leading dot so it is hidden and easy to ignore.
  2. activate puts .venv/bin first on PATH. which python proves it.
  3. requirements.txt states what the project needs (ranges); pip freeze records what is installed (exact pins). Commit the first; commit the second when results must be reproduced exactly.

Visual

Text
ds1-portfolio/
├── .venv/              never committed (large, machine-specific)
├── .gitignore          lists .venv/ and __pycache__/
├── requirements.txt    committed: how to rebuild .venv
├── README.md
└── labs/

Check questions

  1. A learner runs pip install pandas and then python script.py says No module named pandas. Give two likely causes.
  2. Why should .venv/ never be committed? Give two reasons.
  3. What is the difference between numpy>=1.26 and numpy==1.26.4? When would you use each?

2. Git's data model

Theory

Git records the history of a project so that any past state can be recovered, compared or combined with others' work. Learners who understand its data model, not just its commands, can recover from almost any mistake.

Definitions

Definition (object id). Git stores every file version, directory listing and commit as an object whose id is the SHA-1 hash of its content: for a file, $\text{id} = \text{SHA1}(\texttt{"blob "} \Vert \text{len} \Vert \texttt{\textbackslash 0} \Vert \text{content})$.

Symbols: $\Vert$ is concatenation; len is the content length in bytes, written in decimal; \0 is a zero byte.

Plain English: the id is a fingerprint of the content. The same content always gets the same id, and changing one byte changes the id completely.

Definition (commit). An object holding a snapshot (a tree id), the ids of its parent commits, an author, a time and a message.

Definition (branch). A name that points to one commit. Committing on a branch moves the pointer to the new commit. HEAD names the branch you are on.

Consequence: the history is a directed acyclic graph (DAG). Each commit points to its parents; nothing can point to a commit created later, because its id would have to be known before it existed.

Worked example: compute a blob id by hand

Python
import hashlib
content = b"hello\n"                          # 6 bytes
header = b"blob %d\0" % len(content)          # b"blob 6\x00"
hashlib.sha1(header + content).hexdigest()
# 'ce013625030ba8dba906f756967f9e9ca394464a'
Terminal
printf 'hello\n' | git hash-object --stdin
# ce013625030ba8dba906f756967f9e9ca394464a

The two agree. This is why Git can detect corruption: if stored bytes change, their hash no longer matches their id.

Worked example: the three areas

Command Working tree Staging area (index) Repository
edit README.md changed
git add README.md snapshot of the file
git commit -m "..." new commit, branch moves

git status compares the three; git diff shows working tree vs index; git diff --staged shows index vs last commit.

Visual

Three areas

git add copies a file's current content into the staging area; git commit stores the staged snapshot as a commit. Restoring copies a stored version back into the working tree.

Check questions

  1. Two learners create a file with identical content on different laptops. Do the blobs have the same id? Explain from the definition.
  2. Why can a commit never point to a later commit?
  3. Predict what git status shows after you edit a file, git add it, then edit it again.

3. Branches and merges

Theory

Branches let you try changes without breaking working code. Every workshop in this path asks learners to work on a branch and merge it, the same flow used in industry pull requests.

Definitions

Definition (merge base). For commits $a$ and $b$, a best common ancestor: a commit reachable from both, with no other common ancestor that is a descendant of it.

Definition (three-way merge). For each file, compare the merge base $O$ with the two sides $A$ and $B$. Per region: if only one side changed it, take that side; if both made the same change, take it; if both changed it differently, report a conflict.

Plain English: Git asks "what did each side change since they split?" It combines changes on different lines automatically and stops only when both sides changed the same lines.

Definition (fast-forward). If the merge base is the current branch's commit itself, the branch pointer simply moves forward; no merge commit is created.

Worked example: a conflict and its resolution

Starting from commit B where README.md has line 3 empty:

  1. On feature/readme, line 3 becomes Labs from the DS1 path. (commit C).
  2. On main, line 3 becomes Work for group AI-2. (commit D).
  3. git merge feature/readme on main: merge base is B; both sides changed line 3 differently, so Git stops:
Text
<<<<<<< HEAD
Work for group AI-2.
=======
Labs from the DS1 path.
>>>>>>> feature/readme
  1. Edit the file to the intended text, Labs from the DS1 path, group AI-2., remove the markers, then git add README.md and git commit. The result M has two parents, D and C.

Visual

Commit graph

Code: code/figures.py.

Check questions

  1. In the figure, what is the merge base of main before the merge (D) and feature/readme (C)? Why?
  2. If nobody had committed D on main, what would git merge feature/readme do? Would there be a conflict?
  3. Side A changes line 2 and side B changes line 10 of the same file. Is there a conflict? Explain with the three-way rule.

4. GitHub workflow

Theory

GitHub hosts the remote copy of the repository. The portfolio (C7-1) and capstone (C8-1) are judged from it, so it must be tidy from day one.

Definitions

Definition (remote). A named URL of another copy of the repository. origin is the default name.

Definition (push, pull). push sends your new commits to the remote and moves its branch; pull fetches the remote's new commits and merges them into yours.

Worked example: first push

Terminal
git remote add origin https://github.com/<user>/ds1-portfolio.git
git push -u origin main

-u links local main to origin/main, so later a plain git push or git pull knows where to go.

Rules for every workshop repo:

Visual

Push and pull

Your laptop and GitHub hold two copies of the same commit graph. push adds your new commits to GitHub's copy; pull brings GitHub's new commits into yours and merges them.

Check questions

  1. A learner commits an OpenAI API key and then deletes the file in the next commit. Is the key safe? What must they do?
  2. git push is rejected with "fetch first". What happened, and what are the next two commands?
  3. Explain back: why do workshops ask you to open a pull request instead of pushing straight to main? Give two reasons.

Lab

Build your own ds1-portfolio repository following exercises.md, then check it:

Terminal
python lectures/02-dev-environment-git/code/check_repo.py ~/ds1-portfolio

The checker (code/check_repo.py) is tested against a model solution repo in code/test_check_repo.py.