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

PythonPython
14
חלקPart 2: פונקציות וקוד אמיתיFunctions & real code כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

דיבאג עם VS CodeDebugging with VS Code

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

Breakpoints, stepping, watching variables and a method for finding bugs.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • לשחזר: מה בדיוק קרה?Reproduce: what exactly happened?
  • לצמצם: איפה בדיוק?Narrow down: where exactly?
  • נקודת עצירה: לחיצה ליד מספר השורהBreakpoint: click by the line number
  • F5 מתחיל, F10 צעד, F11 נכנס לפונקציהF5 starts, F10 steps, F11 steps in
  • print(f"{x=}") מדפיס שם וערךprint(f"{x=}") prints name and value
  • repr מראה רווחים ומירכאותrepr shows spaces and quotes
  • assert תנאי, "הודעה"assert condition, "message"
  • נכשל מוקדם ובקולFails early and loudly
  • רמות: DEBUG, INFO, WARNING, ERRORLevels: DEBUG, INFO, WARNING, ERROR

מונחיםTerms

  • דיבאגרdebugger: כלי שעוצר את התוכנית באמצע ומאפשר להריץ שורה אחרי שורה ולראות את כל המשתנים.A tool that pauses the program and lets you run it line by line and see every variable.
  • נקודת עצירהbreakpoint: סימון על שורה שבו הדיבאגר יעצור. ב-VS Code: לחיצה משמאל למספר השורה (נקודה אדומה).A mark on a line where the debugger will stop. In VS Code: click left of the line number (a red dot).
  • assertassert: בדיקה בקוד: assert תנאי, "הודעה". אם התנאי לא נכון, התוכנית נעצרת עם AssertionError.A check in code: assert condition, "message". If the condition is false the program stops with AssertionError.
  • logginglogging: מודול לרישום הודעות עם רמות (DEBUG, INFO, WARNING, ERROR), שאפשר להדליק ולכבות בלי למחוק קוד.A module for recording messages with levels (DEBUG, INFO, WARNING, ERROR) that you can switch on and off without deleting code.
  • שיטת הברווזrubber duck debugging: להסביר את הקוד שורה אחרי שורה למישהו (או לברווז גומי). תוך כדי הסבר מגלים את הטעות.Explaining your code line by line to someone (or a rubber duck). While explaining, you spot the mistake.

Cheatsheet

שיטהMethod
def average(nums):
    total = 0
    for n in nums:
        total += n
        print(f"  debug: n={n}, total={total}")
    return total / len(nums) + 1
הדפסותPrints
title = "Dune "
search = "Dune"
print(f"{title=}, {search=}")
print(title == search)
print(repr(title), len(title))
age = "30"
print(f"{age=} {type(age)=}")
assertassert
def percent(read, total):
    assert total > 0, "total pages must be positive"
    assert 0 <= read <= total, f"read={read} is outside 0..{total}"
    return round(read / total * 100)

print(percent(103, 412))
assert percent(0, 10) == 0
logginglogging
import logging
import sys

logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s", stream=sys.stdout)
log = logging.getLogger("shelf")

log.debug("loading file...")
באגים קלאסייםClassic bugs
def total_buggy(nums):
    total = 0
    for n in nums:
        total += n
        return total

def total_fixed(nums):

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorמנחשים ומשנים קוד באקראי במקום לבדוק. הנה בדיקה שמגלה שהתוצאה רחוקה מהציפייה.Guessing and changing code at random instead of checking. Here's a check that shows the result is off.AssertionError: expected 20, got 21.0: ההודעה אומרת בדיוק מה ציפינו ומה קיבלנו. מכאן מתחילים לצמצם.AssertionError: expected 20, got 21.0: the message says exactly what we expected and what we got. Narrowing starts here.
AssertionErrorשמים נקודת עצירה על שורה שאף פעם לא רצה, ומתפלאים שהדיבאגר לא עוצר. כאן ה-if אף פעם לא מתקיים.Putting a breakpoint on a line that never runs, and wondering why it doesn't stop. Here the if never holds.AssertionError: אם הדיבאגר לא עוצר, כנראה שהשורה לא רצה. שמים נקודה מוקדם יותר ובודקים את התנאי.AssertionError: if the debugger doesn't stop, the line probably never runs. Put a breakpoint earlier and check the condition.
AssertionErrorמשווים מחרוזות עם רווח נסתר. בלי repr לא רואים אותו בכלל.Comparing strings with a hidden space. Without repr you can't see it.AssertionError: 'Dune ' != 'Dune': ה-!r (repr) חושף את הרווח. מנקים עם strip() כשקוראים וכששומרים.AssertionError: 'Dune ' != 'Dune': the !r (repr) reveals the space. Clean with strip() when reading and saving.
AssertionErrorהנחה שהופרה: מספר העמודים שקראו גדול מהספר.A broken assumption: more pages read than the book has.AssertionError: read=500 is outside 0..412: הבאג נתפס במקום שבו הוא נכנס, עם הסבר.AssertionError: read=500 is outside 0..412: the bug is caught where it entered, with an explanation.
AttributeErrorטעות כתיב ברמה: אין logging.WARN_ING.A typo in a level name: there's no logging.WARN_ING.AttributeError: module 'logging' has no attribute 'WARN_ING': השמות הם DEBUG, INFO, WARNING, ERROR, CRITICAL.AttributeError: module 'logging' has no attribute 'WARN_ING': the names are DEBUG, INFO, WARNING, ERROR, CRITICAL.
AssertionErroroff-by-one: הלולאה מפספסת את האחרון. בדיקה חושפת.Off-by-one: the loop misses the last item. A check exposes it.AssertionError: counted 6 days, expected 7: range(1, days) עוצר לפני 7. כותבים range(1, days + 1).AssertionError: counted 6 days, expected 7: range(1, days) stops before 7. Write range(1, days + 1).

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