|
1 | 1 | # learn-python |
2 | 2 |
|
3 | | -Interactive Python **memory model** visualizer, sandbox, and challenge levels. |
| 3 | +An interactive **Python memory-model** visualizer, sandbox, and 78-level challenge |
| 4 | +course — where you watch what happens in RAM, not just read about it. |
4 | 5 |
|
5 | 6 | **Live:** https://alisadeghiaghili.github.io/learn-python/ |
6 | 7 |
|
7 | | -Architectural sibling of [learnGitBranching](https://github.com/pcottle/learnGitBranching): a fully client-side simulator with a live canvas, command shell, goal-checked levels, and statement golf. Where LGB makes git's commit DAG visible, learn-python makes Python's stack/heap object graph visible — and lets you watch it become a chart. |
| 8 | +The architectural sibling of [learnGitBranching](https://github.com/pcottle/learnGitBranching): |
| 9 | +a fully client-side simulator with a live canvas, a command shell, and goal-checked |
| 10 | +levels. Where LGB makes git's commit DAG visible, learn-python makes Python's |
| 11 | +stack/heap object graph visible — and lets you watch a plot grow out of that same |
| 12 | +data. |
8 | 13 |
|
9 | | -## Run |
| 14 | +The whole project runs on one idea: **the hard part of Python's data libraries is |
| 15 | +not the API, it is identity.** Does `v` *share* `df`'s buffer or own its own? Is |
| 16 | +`b` a second name for `a`, or a fresh object? The canvas answers it by drawing the |
| 17 | +object graph the way the interpreter holds it, and every level is built to make one |
| 18 | +of those questions *visible*. |
| 19 | + |
| 20 | +## The course |
| 21 | + |
| 22 | +**78 levels across 16 series, in three languages (English, German, Farsi),** |
| 23 | +starting from zero and ramping to a capstone. Each level carries an **ELI band** |
| 24 | +(`ELI5` → `ELI-PHD`) so you know how deep it goes, and the data/concurrency series |
| 25 | +have a **deep lesson** — the full ELI5→ELI-PHD ramp with inline diagrams. |
| 26 | + |
| 27 | +``` |
| 28 | +First Steps → Decisions → Repeating → Functions & Frames |
| 29 | + (print, values, names, math, strings) (if/elif/else) (for/range, while) (def, frames) |
| 30 | + ↓ the memory model arrives |
| 31 | +Names & Bindings → Containers in Memory → Mutation & Methods |
| 32 | + → Aliasing & Copy → Copy Semantics (shallow vs deep) |
| 33 | + → Iterators & Iterables → Defaults & Functional (defaultdict, map, filter) |
| 34 | + ↓ the data libraries |
| 35 | +NumPy: Buffers & Views → Pandas: Tables as windows over a buffer |
| 36 | + ↓ concurrency |
| 37 | +Asyncio (coroutines, tasks, the event loop) |
| 38 | + → Threading (shared state, the data race, locks) |
| 39 | + ↓ |
| 40 | +Plotting & Capstone |
| 41 | +``` |
| 42 | + |
| 43 | +Every level has a brief, an optional hint, a **goal** (a predicate or a target |
| 44 | +memory snapshot), a statement **par** for golf, and a worked solution. The test |
| 45 | +suite runs every solution against its goal, so the entire catalog is proven |
| 46 | +solvable within `par + 2` statements — not merely compilable. |
10 | 47 |
|
11 | | -Open https://alisadeghiaghili.github.io/learn-python/ in a browser. |
| 48 | +## What you see |
12 | 49 |
|
13 | | -Locally, use the Vite dev server (TypeScript ES modules need a bundler): |
| 50 | +Three boards sit side by side, plus a console REPL and a learning-guide panel: |
| 51 | + |
| 52 | +- **Memory** — the core instrument. Stack frames on the left, heap objects on the |
| 53 | + right, amber reference edges between them. Strings are real heap objects, so |
| 54 | + `concat`, `.upper()`, and indexing are all visible. |
| 55 | +- **RAM** — the memory map: hex addresses, byte sizes, refcounts, and contiguous |
| 56 | + buffers. An ndarray view paints its offset/shape window as a strip aligned to the |
| 57 | + buffer's bytes, so a *view* and a *copy* look different at the byte level. |
| 58 | +- **Plot** — `scatter(xs, ys)` and `line(xs, ys, "title")` render the same data as |
| 59 | + SVG. The memory model and the chart read the identical objects, which is the |
| 60 | + point: a plot is just a list of `(x, y)` pairs. |
| 61 | + |
| 62 | +**Watch it run.** Every run records a step trace; the transport bar under the tabs |
| 63 | +(⏮ ◀ ▶ ⏭) scrubs it, so a `for`/`while` loop can be watched iteration by iteration |
| 64 | +on the canvas. Diagrams appear inline in lessons wherever a picture beats a |
| 65 | +paragraph. |
| 66 | + |
| 67 | +## Run |
| 68 | + |
| 69 | +Open https://alisadeghiaghili.github.io/learn-python/ in a browser, or run it |
| 70 | +locally (TypeScript ES modules need a bundler): |
14 | 71 |
|
15 | 72 | ```bash |
16 | 73 | npm install |
17 | | -npm run dev |
18 | | -# → http://127.0.0.1:5173 |
| 74 | +npm run dev # → http://127.0.0.1:5173 |
19 | 75 | ``` |
20 | 76 |
|
21 | 77 | ## Test |
22 | 78 |
|
23 | 79 | ```bash |
24 | | -npm test # vitest run |
25 | | -npm run build # type-check (tsc --noEmit) + production build to dist/ |
| 80 | +npm test # vitest run — 138 tests |
| 81 | +npm run build # type-check (tsc --noEmit) + production build to dist/ |
26 | 82 | ``` |
27 | 83 |
|
28 | | -## Layout |
29 | | - |
30 | | -Two live surfaces sit side by side: |
31 | | - |
32 | | -- **Memory** — stack frames on the left, heap objects on the right, amber reference edges between them. This is the core instrument. |
33 | | -- **Plot** — `scatter(xs, ys)` and `line(xs, ys, "title")` push a plot spec that renders as SVG on this tab. The memory model and the chart read the same data, which is the pedagogical point: a plot is just a list of `(x, y)` pairs. |
34 | | - |
35 | | -Plus a **console** REPL at the bottom (statement or meta-command) and a **learning guide** panel on the right with the level brief, par, and next hint. |
36 | | - |
37 | 84 | ## Sandbox |
38 | 85 |
|
39 | | -Type Python-subset statements. Meta-commands: |
| 86 | +Free-play mode: type Python-subset statements. Meta-commands: |
40 | 87 |
|
41 | 88 | | Command | Effect | |
42 | 89 | |---------|--------| |
43 | | -| `help` | subset + meta overview | |
| 90 | +| `help` | the subset + meta overview | |
44 | 91 | | `levels` | list the 78 levels / 16 series | |
45 | 92 | | `level <id>` | load a level (e.g. `level first-name`) | |
46 | | -| `lesson` | open the current level's lesson text | |
| 93 | +| `lesson` | open the current level's lesson | |
47 | 94 | | `goal` / `guide` | focus the right-hand guide panel | |
48 | | -| `hint` | level hint | |
| 95 | +| `hint` | the level hint | |
49 | 96 | | `solution` | reveal the solution | |
50 | 97 | | `golf` | statements used vs par | |
51 | | -| `undo` | undo last statement | |
52 | | -| `reset` | reset level / sandbox | |
| 98 | +| `undo` | undo the last statement | |
| 99 | +| `reset` | reset the level / sandbox | |
53 | 100 | | `sandbox` | free-play mode | |
54 | 101 | | `script` | toggle the multi-line script editor | |
55 | 102 | | `clear` | clear the console | |
56 | 103 |
|
57 | | -## Supported Python (v0) |
58 | | - |
59 | | -A deliberately small, pedagogically sharp subset — not CPython: |
60 | | - |
61 | | -- **Literals & types:** `int`, `float`, `str`, `bool`, `None`; `list`, `dict`, `tuple`, `set` |
62 | | -- **Names:** assignment, rebinding, augmented assign, indexing, slicing |
63 | | -- **Control flow:** `if` / `elif` / `else`, `for x in …`, `while …`, `break`, `continue`; `range(n)` / `range(a, b)` / `range(a, b, step)` |
64 | | -- **Methods:** `.append` `.insert` `.extend` `.pop` `.remove` `.copy` `.get` `.update` `.keys` `.clear` |
65 | | -- **Functions:** `def` / call / `return`, local frames, nested calls |
66 | | -- **Builtins:** `print` `len` `type` `id` `str` `int` `bool` `list` `dict` `set` |
67 | | -- **Modules:** `import copy as cp` — `cp.copy` (shallow) and `cp.deepcopy`; `import collections as c` — `c.defaultdict`; `import functools as f` — `f.reduce`; `import numpy as np` — `np.array`, `.copy()`, slicing (views), `+`, `.sum()`; `import pandas as pd` — `pd.DataFrame`, `pd.Series`, `pd.read_csv`; `import asyncio as a`, `import threading as t` |
68 | | -- **Iterators:** `iter(x)` and `next(it)` — a stateful iterator object you advance by hand |
69 | | -- **Functional:** `map(fn, it)` / `filter(pred, it)` — lazy iterator objects; `f.reduce(fn, it)` — an eager fold |
70 | | -- **NumPy:** `np.array` → an ndarray *window* over a separate **buffer** box; `.copy()` mints a new buffer; a slice is a *view* sharing the same buffer; `a + 1` vectorizes into a new buffer; `a.sum()` folds to a scalar |
71 | | -- **Plotting:** `scatter(xs, ys, "title")` `line(xs, ys, "title")` |
72 | | -- **Operators:** arithmetic, comparisons, `is`, `==`, `and` / `or` / `not`, `in` / `not in` |
73 | | - |
74 | | -**Watch it run:** every run records a step trace; the transport bar under the board tabs (⏮ ◀ ▶ ⏭) scrubs it, so a `for`/`while` loop can be watched iteration by iteration on the canvas. |
75 | | - |
76 | | -Not in v0: classes, real module imports (only the simulated `copy`, `collections`, `functools`, `numpy`, `pandas`, `asyncio`, `threading`), exceptions (beyond clean parse/runtime errors), comprehensions, real I/O, full CPython semantics. |
77 | | - |
78 | | -A planned curriculum extends this with pandas, re, datetime and more — all drawn on the same memory canvas. See `docs/ENGINE-EXTENSION.md` and `docs/adr/002-library-modules.md`. |
| 104 | +## The Python subset |
| 105 | + |
| 106 | +A deliberately small, pedagogically sharp subset — a hand-written **teaching |
| 107 | +simulator**, not CPython. Every state transition is controlled so the visualizer |
| 108 | +can show what a real interpreter hides. |
| 109 | + |
| 110 | +- **Literals & types** — `int`, `float`, `str`, `bool`, `None`; `list`, `dict`, |
| 111 | + `tuple`, `set` |
| 112 | +- **Names** — assignment, rebinding, augmented assign, indexing, slicing |
| 113 | +- **Control flow** — `if` / `elif` / `else`, `for x in …`, `while …`, `break`, |
| 114 | + `continue`; `range(n)`, `range(a, b)`, `range(a, b, step)` |
| 115 | +- **String methods** — `.upper`, `.lower` |
| 116 | +- **List methods** — `.append`, `.insert`, `.extend`, `.pop`, `.remove`, `.copy`, |
| 117 | + `.clear` |
| 118 | +- **Dict methods** — `.get`, `.update`, `.keys`, `.clear` |
| 119 | +- **Functions** — `def` / `async def`, calls, `return`, local frames, nested calls |
| 120 | +- **Builtins** — `print`, `len`, `type`, `id`, `int`, `str`, `bool`, `range`, |
| 121 | + `iter`, `next`, `map`, `filter`, `reduce`, `list`, `dict`, `set`, `scatter`, |
| 122 | + `line` |
| 123 | +- **Operators** — arithmetic, comparisons, `is`, `==`, `and` / `or` / `not`, |
| 124 | + `in` / `not in` |
| 125 | +- **Iterators & functional** — `iter(x)` / `next(it)` (a stateful cursor you |
| 126 | + advance by hand); `map(fn, it)` / `filter(pred, it)` are lazy iterator objects; |
| 127 | + `reduce` is an eager fold |
| 128 | + |
| 129 | +**Simulated libraries** — `import X` binds a module whose methods are taught for |
| 130 | +their *memory model*, not their full API: |
| 131 | + |
| 132 | +| Import | Taught for | |
| 133 | +|--------|-----------| |
| 134 | +| `import copy as cp` | `cp.copy` (shallow) vs `cp.deepcopy` | |
| 135 | +| `import collections as c` | `c.defaultdict` | |
| 136 | +| `import functools as f` | `f.reduce` | |
| 137 | +| `import numpy as np` | `np.array` → an ndarray *window* over a separate **buffer** box; `.copy()` mints a new buffer; a slice is a *view* sharing the buffer; `a + 1` vectorizes into a new buffer; `.sum()` | |
| 138 | +| `import pandas as pd` | `pd.DataFrame` / `pd.Series` / `pd.read_csv`; `df.iloc[a:b]` is a true *view* (a write through it lands in the frame); `.copy()` is a new buffer; `df["col"]` → Series | |
| 139 | +| `import asyncio as a` | `async def`, `a.create_task`, `a.run` — a tick-based event loop that round-robins tasks to their next `await`, so two tasks visibly interleave | |
| 140 | +| `import threading as t` | `t.Thread` / `t.Lock`, `.start()` / `.join()`, `.acquire()` / `.release()` — threads share the heap and interleave on it; a held lock blocks the caller (the data race, made visible) | |
| 141 | + |
| 142 | +**Not in this version:** classes, real module imports, exceptions (beyond clean |
| 143 | +parse/runtime errors), comprehensions, real I/O, and full CPython semantics. The |
| 144 | +curriculum roadmap (re, datetime, pytz, requests, SQLAlchemy, pyodbc, |
| 145 | +multiprocessing, matplotlib, plotly) extends the same canvas — see |
| 146 | +[docs/CURRICULUM.md](docs/CURRICULUM.md). |
79 | 147 |
|
80 | 148 | ## Architecture |
81 | 149 |
|
82 | 150 | ``` |
83 | | -src/engine/ simulated runtime (tokenizer, parser, evaluator, memory, session) |
84 | | - + goal checks (checks.ts) — the "TreeCompare" analogue |
85 | | -src/levels/ 16-series / 78-level catalog + per-level goals, par, solutions |
86 | | -src/ui/ app shell, memory canvas, plot board, REPL, dialog, script editor |
| 151 | +src/engine/ the simulated runtime — tokenizer, parser, evaluator, memory model, |
| 152 | + record-replay stepper — plus goal checks (checks.ts), the |
| 153 | + "TreeCompare" analogue |
| 154 | +src/levels/ the 16-series / 78-level catalog: one file per series, each with |
| 155 | + goals, par, solutions, and deep lessons |
| 156 | +src/ui/ app shell, memory canvas, RAM board, plot board, schematic (SVG) |
| 157 | + engine, REPL, dialogs, script editor |
| 158 | +src/i18n/ the full trilingual copy (English is the source of truth) |
87 | 159 | src/style.css design tokens + layout |
88 | | -tests/ vitest unit + level-solution tests |
| 160 | +tests/ vitest unit, level-solution, schematic, and i18n-coverage tests |
89 | 161 | ``` |
90 | 162 |
|
91 | | -Mirrors LGB's separation: `engine` / `visuals` / `levels` / `command line`. |
92 | | - |
93 | | -The engine is intentionally a **teaching subset**, not CPython. Every state transition is controlled so the visualizer can show what a real interpreter hides. |
| 163 | +Mirrors LGB's separation of `engine` / `visuals` / `levels` / `command line`. |
94 | 164 |
|
95 | | -## Levels |
96 | | - |
97 | | -Sixteen series, 78 levels. The course now starts **from zero**: a pure-Python |
98 | | -spine — **First Steps** (print, values, names, math, strings), **Decisions** |
99 | | -(`if`/`elif`/`else`, booleans, comparisons), **Repeating** (`for`/`range`, |
100 | | -`while`, building data, and a "watch the loop run" level), and **Functions & |
101 | | -Frames** — reached before any memory-model vocabulary. Only then does the |
102 | | -memory model arrive: **Names & Bindings**, **Containers in Memory**, **Mutation |
103 | | -& Methods**, **Aliasing & Copy**, **Copy Semantics** (shallow vs deep), |
104 | | -**Iterators & Iterables**, **Defaults & Functional** (defaultdict, map, filter). |
105 | | -Then the data libraries — **NumPy: Buffers & Views**, **Pandas: Tables as |
106 | | -windows over a buffer** — and concurrency — **Asyncio** (coroutines, tasks, the |
107 | | -event loop) and **Threading** (threads, shared state, the data race) — closing |
108 | | -with **Plotting & Capstone**. |
| 165 | +## Tech |
109 | 166 |
|
110 | | -Each level has a brief, optional hint, a goal (predicate or target snapshot), a |
111 | | -statement-par for golf, and a worked solution. Every level's own solution is |
112 | | -verified to solve its goal within `par + 2` statements, so the whole catalog is |
113 | | -proven runnable, not just compilable. |
| 167 | +TypeScript, Vite, Vitest. **No backend, no runtime dependency** — the |
| 168 | +"interpreter" is a hand-written subset whose entire memory graph is inspectable in |
| 169 | +the browser. |
114 | 170 |
|
115 | | -## Tech |
| 171 | +## Docs |
116 | 172 |
|
117 | | -TypeScript, Vite, Vitest. No backend, no runtime dependency — the "interpreter" is a hand-written subset whose entire memory graph is inspectable in the browser. |
| 173 | +- [docs/CURRICULUM.md](docs/CURRICULUM.md) — the design doc: the thesis, the |
| 174 | + 0→90 ladder, the ELI bands, the enabling infrastructure, the full catalog, and |
| 175 | + the roadmap. |
| 176 | +- [docs/ENGINE-EXTENSION.md](docs/ENGINE-EXTENSION.md) — how to add a library to |
| 177 | + the engine and canvas. |
| 178 | +- [docs/adr/](docs/adr/) — architecture decision records (the simulated subset, |
| 179 | + library modules, control flow + record-replay). |
118 | 180 |
|
119 | 181 | ## License |
120 | 182 |
|
121 | | -MIT |
| 183 | +[MIT](LICENSE) |
0 commit comments