נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
31
חלקPart 5: בונים דבריםBuilding things כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

פרויקט אמצעMidterm project

מחברים הכול לגרסה 1.0, עם תכנון, בדיקות והצגה.

Put it all together into version 1.0, with planning, tests and a demo.

01לתכנן לפני שכותביםPlan before you code

פרויקט האמצע מחבר את כל מה שלמדתם לכלי אחד: "מדף 1.0", ספרייה אישית מהטרמינל. מתחילים בתכנון: משפט אחד שמסביר מה הכלי עושה, MVP עם מינימום פקודות, ורשימה של רעיונות ל"אחר כך" כדי שהם לא יתקעו את הגרסה הראשונה. התכנון הוא קוד בפני עצמו: רשימת פקודות שאפשר לבדוק.

The midterm project joins everything you've learned into one tool: "Shelf 1.0", a personal library in the terminal. Start by planning: one sentence describing what the tool does, an MVP with the fewest commands, and a "later" list so ideas don't hold up the first version. The plan is code in itself: a list of commands you can check.

plan.py
PLAN = {
    "pitch": "Track the books I read, from the terminal",
    "mvp": ["add TITLE AUTHOR PAGES", "read TITLE PAGES", "stats"],
    "later": ["search", "tags", "charts", "API", "goals"],
}
print(PLAN["pitch"])
for i, cmd in enumerate(PLAN["mvp"], 1):
    print(f"  {i}. shelf {cmd}")
print("later:", ", ".join(PLAN["later"]))
פלטOutput
Track the books I read, from the terminal
  1. shelf add TITLE AUTHOR PAGES
  2. shelf read TITLE PAGES
  3. shelf stats
later: search, tags, charts, API, goals
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

MVP הוא כמו אופניים לפני מכונית: גם האופניים לוקחים אתכם ממקום למקום, ומהם לומדים מה באמת צריך.

An MVP is like a bicycle before a car: the bike also gets you from A to B, and teaches you what you really need.

טעות נפוצהCommon mistake

מתחילים מכל הפיצ'רים ביחד, ואף אחד לא עובד עד הסוף.

Starting with every feature at once, so none works fully.

plan.py
features = {"add": 0.6, "read": 0.5, "stats": 0.4, "search": 0.3, "charts": 0.2, "api": 0.1}
working = [f for f, done in features.items() if done == 1]
assert working, f"six features started, {len(working)} finished: finish the MVP first"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/plan.py", line 3, in <module>
    assert working, f"six features started, {len(working)} finished: finish the MVP first"
           ^^^^^^^
AssertionError: six features started, 0 finished: finish the MVP first
בעברית פשוטה: In plain words: AssertionError: six features started, 0 finished: ...: מסיימים פקודה אחת עד הסוף (כולל בדיקה), ורק אז עוברים לבאה.AssertionError: six features started, 0 finished: ...: finish one command completely (tests included), then move on.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

02מבנה הפרויקטProject structure

הפרדת אחריות: כל קובץ יודע דבר אחד. models.py מגדיר מה זה ספר, storage.py יודע לשמור ולטעון, ו-cli.py מדבר עם המשתמש. כך אפשר להחליף את האחסון ל-SQLite (מפגש 23) בלי לגעת בממשק, או להוסיף API (מפגש 29) שמשתמש באותו מודל ואחסון. שלושת הקבצים:

Separation of concerns: each file knows one thing. models.py defines what a book is, storage.py knows how to save and load, and cli.py talks to the user. That way you can swap storage for SQLite (session 23) without touching the interface, or add an API (session 29) that reuses the same model and storage. The three files:

models.py
from dataclasses import dataclass, field, asdict


@dataclass
class Book:
    title: str
    author: str
    pages: int
    read: int = 0
    tags: list[str] = field(default_factory=list)

    def progress(self) -> int:
        return round(self.read / self.pages * 100) if self.pages else 0

    def to_dict(self) -> dict:
        return asdict(self)
storage.py
import json
from pathlib import Path

from models import Book


def load(path: Path) -> list[Book]:
    if not path.exists():
        return []
    return [Book(**d) for d in json.loads(path.read_text(encoding="utf-8"))]


def save(path: Path, books: list[Book]) -> None:
    tmp = path.with_suffix(".tmp")
    tmp.write_text(json.dumps([b.to_dict() for b in books], indent=2, ensure_ascii=False), encoding="utf-8")
    tmp.replace(path)
Terminal
ls
python3 -c "import models, storage, cli; print('imports ok')"
פלטOutput
$ ls
cli.py
models.py
storage.py
test_shelf.py
$ python3 -c "import models, storage, cli; print('imports ok')"
imports ok
אנלוגיה מהחייםReal-life analogy

פרויקט מחולק לקבצים הוא כמו מטבח של מסעדה: עמדת סלטים, עמדת גריל, עמדת קינוחים. כל אחד יודע את העבודה שלו, ויחד יוצאת ארוחה.

A project split into files is like a restaurant kitchen: a salad station, a grill station, a dessert station. Each knows its job, and together a meal comes out.

טעות נפוצהCommon mistake

ייבוא מעגלי: models מייבא מ-storage, ו-storage מ-models.

A circular import: models imports from storage, and storage from models.

Terminal
python3 -c "import models"
מה הטרמינל עונהWhat the terminal says
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import models
  File "/Users/you/python-course/models.py", line 1, in <module>
    from storage import save
  File "/Users/you/python-course/storage.py", line 1, in <module>
    from models import Book
ImportError: cannot import name 'Book' from 'models' (consider renaming '/Users/you/python-course/models.py' if it has the same name as a library you intended to import)
בעברית פשוטה: In plain words: ImportError: cannot import name 'Book' from 'models': models מייבא את storage, ו-storage מבקש את Book מ-models שעוד לא סיים להיטען. השכבות צריכות להיות בכיוון אחד: cli → storage → models. המודל לא יודע כלום על אחסון.ImportError: cannot import name 'Book' from 'models': models imports storage, and storage asks for Book from models, which hasn't finished loading. Layers must point one way: cli → storage → models. The model knows nothing about storage.

מפצלים קוד לפונקציות קטנות שקל לבדוק.

Split code into small functions that are easy to check.

עוד דוגמה: פונקציה אחת, אחריות אחתOne more: one function, one job
example.py
def parse(line):
    title, pages = line.split(",")
    return title.strip(), int(pages)

def total_pages(lines):
    return sum(parse(l)[1] for l in lines)

print(total_pages(["Dune, 412", "Emma, 474"]))
פלטOutput
886
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03הממשק: cli.pyThe interface: cli.py

cli.py מחבר הכול: מפרש את הפקודה (מפגש 27), טוען את המדף, משנה, ושומר. שימו לב שהלוגיקה פשוטה, כי הנתונים והשמירה כבר מחוץ לקובץ. הנה הקוד והרצה אמיתית שלו:

cli.py ties it all together: parses the command (session 27), loads the shelf, changes it, and saves. Notice how simple the logic is, because data and storage already live outside this file. Here's the code and a real run:

cli.py
import argparse
import sys
from pathlib import Path

from models import Book
from storage import load, save

DATA = Path("shelf.json")


def main(argv=None) -> int:
    p = argparse.ArgumentParser(prog="shelf")
    sub = p.add_subparsers(dest="cmd", required=True)
    a = sub.add_parser("add")
    a.add_argument("title")
    a.add_argument("author")
    a.add_argument("pages", type=int)
    r = sub.add_parser("read")
    r.add_argument("title")
    r.add_argument("pages", type=int)
    sub.add_parser("stats")
    args = p.parse_args(argv)

    books = load(DATA)
    if args.cmd == "add":
        books.append(Book(args.title, args.author, args.pages))
        print(f"added {args.title}")
    elif args.cmd == "read":
        book = next((b for b in books if b.title.lower() == args.title.lower()), None)
        if book is None:
            print(f"not found: {args.title}", file=sys.stderr)
            return 1
        book.read = min(book.pages, book.read + args.pages)
        print(f"{book.title}: {book.progress()}%")
    else:
        total = sum(b.pages for b in books)
        done = sum(b.read for b in books)
        print(f"{len(books)} books, {done}/{total} pages ({round(done / total * 100) if total else 0}%)")
    save(DATA, books)
    return 0


if __name__ == "__main__":
    sys.exit(main())
Terminal
python3 cli.py add Dune "Frank Herbert" 412
python3 cli.py add Matilda "Roald Dahl" 240
python3 cli.py read dune 103
python3 cli.py read emma 10
echo "exit: $?"
python3 cli.py stats
cat shelf.json
פלטOutput
$ python3 cli.py add Dune "Frank Herbert" 412
added Dune
$ python3 cli.py add Matilda "Roald Dahl" 240
added Matilda
$ python3 cli.py read dune 103
Dune: 25%
$ python3 cli.py read emma 10
not found: emma
$ echo "exit: $?"
exit: 1
$ python3 cli.py stats
2 books, 103/652 pages (16%)
$ cat shelf.json
[
  {
    "title": "Dune",
    "author": "Frank Herbert",
    "pages": 412,
    "read": 103,
    "tags": []
  },
  {
    "title": "Matilda",
    "author": "Roald Dahl",
    "pages": 240,
    "read": 0,
    "tags": []
  }
]
אנלוגיה מהחייםReal-life analogy

cli.py הוא כמו פקיד קבלה: הוא לא מבשל ולא מנקה, רק מקבל בקשות ומעביר אותן למי שאחראי.

cli.py is like a receptionist: doesn't cook or clean, just takes requests and passes them to whoever is responsible.

טעות נפוצהCommon mistake

שומרים את המדף לפני שבודקים שהפקודה הצליחה, ודורסים נתונים.

Saving the shelf before checking the command succeeded, overwriting data.

cli.py
books = ["Dune", "Matilda"]
saved = list(books)
books.clear()
saved = list(books)
assert saved, "an error midway emptied the list, and it was saved anyway: save only after success"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/cli.py", line 5, in <module>
    assert saved, "an error midway emptied the list, and it was saved anyway: save only after success"
           ^^^^^
AssertionError: an error midway emptied the list, and it was saved anyway: save only after success
בעברית פשוטה: In plain words: AssertionError: an error midway emptied the list, ...: שומרים רק בסוף, אחרי שכל השלבים הצליחו (ובכתיבה לקובץ זמני, כמו ב-storage.py).AssertionError: an error midway emptied the list, ...: save only at the end, after every step succeeded (and via a temp file, as in storage.py).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04בדיקות לכל הפרויקטTests for the whole project

לפרויקט אמיתי צריך בדיקות שמכסות כל שכבה. pytest נותן fixtures מובנים: tmp_path הוא תיקייה זמנית ריקה, monkeypatch מחליף זמנית את cli.DATA כדי שהבדיקה לא תיגע בקובץ האמיתי, ו-capsys אוסף את מה שהודפס. כאן הבדיקות רצות על הפרויקט:

A real project needs tests covering every layer. pytest offers built-in fixtures: tmp_path is an empty temporary folder, monkeypatch temporarily swaps cli.DATA so the test never touches the real file, and capsys collects what was printed. Here the tests run on the project:

test_shelf.py
from pathlib import Path

import cli
from models import Book
from storage import load, save


def test_progress():
    assert Book("A", "B", 200, 50).progress() == 25
    assert Book("A", "B", 0).progress() == 0


def test_round_trip(tmp_path):
    path = tmp_path / "s.json"
    save(path, [Book("Dune", "Frank Herbert", 412, tags=["sci-fi"])])
    assert load(path) == [Book("Dune", "Frank Herbert", 412, tags=["sci-fi"])]


def test_cli_flow(tmp_path, monkeypatch, capsys):
    monkeypatch.setattr(cli, "DATA", tmp_path / "shelf.json")
    assert cli.main(["add", "Dune", "Frank Herbert", "400"]) == 0
    assert cli.main(["read", "dune", "100"]) == 0
    assert cli.main(["read", "Emma", "5"]) == 1
    cli.main(["stats"])
    assert capsys.readouterr().out.splitlines()[-1] == "1 books, 100/400 pages (25%)"
Terminal
python3 -m pytest -v --no-header -p no:cacheprovider
פלטOutput
============================= test session starts ==============================
collecting ... collected 3 items

test_shelf.py::test_progress PASSED                                      [ 33%]
test_shelf.py::test_round_trip PASSED                                    [ 66%]
test_shelf.py::test_cli_flow PASSED                                      [100%]

============================== 3 passed in 0.01s ===============================
אנלוגיה מהחייםReal-life analogy

monkeypatch הוא כמו להחליף את המים בבקבוק במים צבועים לניסוי: אותו בקבוק, אותה תנועה, אבל רואים בדיוק לאן הכול זורם, ובסוף מחזירים.

monkeypatch is like swapping a bottle's water for dyed water in an experiment: same bottle, same flow, but you see exactly where it goes, and then put it back.

טעות נפוצהCommon mistake

בדיקה שכותבת לקובץ האמיתי של המשתמש.

A test that writes to the user's real file.

Terminal
python3 -m pytest -q --tb=line -p no:cacheprovider
מה הטרמינל עונהWhat the terminal says
F                                                                        [100%]
=================================== FAILURES ===================================
E   AssertionError: the test wrote into the real shelf.json
    assert 'Test book' not in '[\n  {\n   ...: []\n  }\n]'
      
      'Test book' is contained here:
        [
          {
            "title": "Test book",
      ?               +++++++++
            "author": "Me",...
      
      ...Full output truncated (5 lines hidden), use '-vv' to show
----------------------------- Captured stdout call -----------------------------
added Test book
/Users/you/python-course/test_shelf.py:7: AssertionError: the test wrote into the real shelf.json
=========================== short test summary info ============================
FAILED test_shelf.py::test_add - AssertionError: the test wrote into the real...
1 failed in 0.01s
בעברית פשוטה: In plain words: AssertionError: the test wrote into the real shelf.json: בדיקה שנוגעת בנתונים אמיתיים עלולה למחוק אותם. משתמשים ב-tmp_path וב-monkeypatch.AssertionError: the test wrote into the real shelf.json: a test touching real data may destroy it. Use tmp_path and monkeypatch.

05READMEREADME

README הוא חלון הראווה של הפרויקט, והדבר הראשון שמראיין רואה ב-GitHub. שלושה חלקים מספיקים: משפט מה הכלי עושה, איך מתקינים, ואיך משתמשים (עם דוגמה אמיתית). אפשר אפילו לבדוק בקוד שלא שכחתם חלק:

A README is the project's shop window, and the first thing an interviewer sees on GitHub. Three parts are enough: a sentence on what the tool does, how to install, and how to use it (with a real example). You can even check in code that you didn't forget a part:

readme_check.py
README = """# Shelf

Track the books you read, from the terminal.

## Install

    python3 -m venv .venv
    source .venv/bin/activate
    pip install pytest

## Usage

    python3 cli.py add Dune "Frank Herbert" 412
    python3 cli.py read dune 103
    python3 cli.py stats

## Tests

    python3 -m pytest
"""

headings = [line[3:] for line in README.splitlines() if line.startswith("## ")]
missing = {"Install", "Usage", "Tests"} - set(headings)
print("headings:", headings)
print("missing:", missing or "nothing")
פלטOutput
headings: ['Install', 'Usage', 'Tests']
missing: nothing
אנלוגיה מהחייםReal-life analogy

README הוא כמו הכריכה האחורית של ספר: בכמה שורות מבינים אם זה בשבילכם ואיך מתחילים.

A README is like a book's back cover: in a few lines you know whether it's for you and how to start.

טעות נפוצהCommon mistake

README בלי הוראות התקנה.

A README without install instructions.

readme_check.py
readme = "# Shelf\n\nA cool tool!\n"
assert "## Install" in readme, "a stranger can't run the project: add an Install section"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/readme_check.py", line 2, in <module>
    assert "## Install" in readme, "a stranger can't run the project: add an Install section"
           ^^^^^^^^^^^^^^^^^^^^^^
AssertionError: a stranger can't run the project: add an Install section
בעברית פשוטה: In plain words: AssertionError: a stranger can't run the project: ...: מה שברור לכם לא ברור לאחרים. כותבים כל צעד, כולל venv.AssertionError: a stranger can't run the project: ...: what's obvious to you isn't to others. Write every step, venv included.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06הגשה ומחווןSubmission and rubric

לפני הגשה עוברים על המחוון. הנה המחוון של מדף 1.0, וקוד קטן שמחשב ציון מתוך רשימת בדיקה. התרגילים במפגש הזה הם החלקים של הפרויקט, ואת הפרויקט השלם מעלים ל-GitHub.

Before submitting, go through the rubric. Here's Shelf 1.0's rubric, and a little code that computes a score from a checklist. This session's exercises are the project's parts, and the full project goes up to GitHub.

קריטריוןCriterionנקודותPointsמה בודקיםWhat's checked
עובדWorks30שלוש הפקודות, כולל ספר שלא קייםAll three commands, including a missing book
מבנהStructure20models / storage / cli, בלי ייבוא מעגליmodels / storage / cli, no circular import
בדיקותTests20לפחות 5, עוברות, לא נוגעות בקובץ אמיתיAt least 5, passing, never touching the real file
עמידותRobustness10קובץ חסר או פגום לא מקריסA missing or broken file doesn't crash
READMEREADME10התקנה, שימוש, בדיקותInstall, usage, tests
GitGit10לפחות 5 commits עם הודעות ברורותAt least 5 commits with clear messages
rubric.py
RUBRIC = {"works": 30, "structure": 20, "tests": 20, "robust": 10, "readme": 10, "git": 10}

def score(checks):
    return sum(points for name, points in RUBRIC.items() if checks.get(name))

mine = {"works": True, "structure": True, "tests": True, "robust": False, "readme": True, "git": True}
print(score(mine), "/", sum(RUBRIC.values()))
print("to fix:", [n for n in RUBRIC if not mine.get(n)])
פלטOutput
90 / 100
to fix: ['robust']
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

מחוון הוא כמו רשימת ציוד לטיול: עוברים עליה לפני היציאה, ולא מגלים בשטח ששכחתם את המים.

A rubric is like a hiking packing list: check it before leaving, rather than discovering on the trail that you forgot water.

טעות נפוצהCommon mistake

שוכחים שקובץ פגום מקריס את הכלי.

Forgetting that a broken file crashes the tool.

storage.py
import json
from pathlib import Path
Path("shelf.json").write_text("[{\"title\": \"Dune\",")
books = json.loads(Path("shelf.json").read_text())
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/storage.py", line 4, in <module>
    books = json.loads(Path("shelf.json").read_text())
  File "/usr/local/lib/python3.13/json/__init__.py", line 352, in loads
    return _default_decoder.decode(s)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^
  File "/usr/local/lib/python3.13/json/decoder.py", line 345, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/json/decoder.py", line 361, in raw_decode
    obj, end = self.scan_once(s, idx)
               ~~~~~~~~~~~~~~^^^^^^^^
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 19 (char 18)
בעברית פשוטה: In plain words: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 20 (char 19): זה 10 נקודות במחוון. עוטפים את הטעינה ב-try (מפגש 21) ומציגים הודעה ברורה.json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 20 (char 19): that's 10 rubric points. Wrap loading in try (session 21) and show a clear message.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich