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

PythonPython
32
חלקPart 6: Python בעידן ה-AI וקריירהPython in the AI era & career כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

עבודה נכונה עם עוזר AI לקודWorking well with an AI coding assistant

מתי לסמוך, איך לבדוק, איך לבקש, ואיך לא לאבד את ההבנה.

When to trust it, how to verify, how to ask, and how not to lose understanding.

או Ctrl+Por Ctrl+P

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

  • מצוין: טיוטה, הסבר, רעיונות, קוד חוזרGreat at: drafts, explanations, ideas, boilerplate
  • חלש: אחריות, הקשר שלא נתתם, עובדות עדכניותWeak at: responsibility, context you didn't give, current facts
  • הקשר: מה הפרויקט, איזו גרסהContext: what the project is, which version
  • דוגמת קלט ופלטAn input and output example
  • סקירה: האם אני מבין כל שורה?Review: do I understand every line?
  • מריצים על מקרי קצהRun it on edge cases
  • כותבים מפרט כבדיקותWrite the spec as tests
  • נותנים לעוזר את הבדיקותGive the assistant the tests
  • פונקציות וחבילות מומצאותMade-up functions and packages

מונחיםTerms

  • עוזר AI לקודAI coding assistant: מודל שפה שמציע, מסביר ומשנה קוד לפי בקשה בשפה רגילה, בתוך העורך או בצ'אט.A language model that suggests, explains and changes code from plain-language requests, in the editor or a chat.
  • בקשה (prompt)prompt: הטקסט שנותנים למודל: מה רוצים, הקשר, דוגמאות ואילוצים. בקשה טובה = תשובה טובה יותר.The text you give the model: what you want, context, examples and constraints. A better prompt = a better answer.
  • המצאה (hallucination)hallucination: תשובה שנשמעת בטוחה אבל שגויה: פונקציה שלא קיימת, חבילה מומצאת, עובדה לא נכונה.An answer that sounds confident but is wrong: a function that doesn't exist, a made-up package, a false fact.
  • סקירת קודcode review: קריאה ביקורתית של קוד לפני שמקבלים אותו: נכונות, מקרי קצה, קריאות ואבטחה.Critically reading code before accepting it: correctness, edge cases, readability and security.
  • מפרט (spec)spec: תיאור מדויק של מה שהקוד צריך לעשות, כולל מקרי קצה. בדיקות הן מפרט שאפשר להריץ.A precise description of what code must do, edge cases included. Tests are a spec you can run.

Cheatsheet

תפקידRole
def average_rating(books):
    """Average rating of the books that have one."""
    total = 0
    for b in books:
        total += b["rating"]
    return round(total / len(books), 1)
בקשהPrompting
def make_prompt(task, context, examples, rules):
    lines = [f"Context: {context}", f"Task: {task}", "Examples:"]
    lines += [f"  {inp!r} -> {out!r}" for inp, out in examples]
    lines += ["Rules:"] + [f"  - {r}" for r in rules]
    return "\n".join(lines)

print(make_prompt(
סקירהReview
def average_rating(books: list[dict]) -> float | None:
    """Average rating of the books that have one, or None if none do."""
    ratings = [b["rating"] for b in books if "rating" in b]
    if not ratings:
        return None
    return round(sum(ratings) / len(ratings), 1)
בדיקותTests
def tests(slugify):
    cases = {"The Little Prince": "the-little-prince", "  Dune  ": "dune", "Hello, World!": "hello-world", "": ""}
    return [text for text, want in cases.items() if slugify(text) != want]

def suggestion_a(text):
    return text.lower().replace(" ", "-")
המצאותHallucinations
import inspect

claims = [("str", "title"), ("str", "capitalize_words"), ("list", "sort"), ("list", "sorted"), ("dict", "get"), ("dict", "find")]
for type_name, method in claims:
    real = hasattr(eval(type_name), method)
    print(f"{type_name}.{method}:", "exists" if real else "DOES NOT EXIST")
print(inspect.signature(sorted))
אבטחהSecurity
import re

PATTERNS = {
    "API key": r"\b(sk|pk)[-_][A-Za-z0-9_-]{12,}",
    "password": r"(?i)password\s*[:=]\s*\S+",
    "email": r"[\w.+-]+@[\w-]+\.[\w.]+",
}

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

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
KeyErrorמקבלים את הקוד בלי לבדוק מקרי קצה.Accepting the code without checking edge cases.KeyError: 'rating': התיעוד אמר "שיש להם דירוג" אבל הקוד לא מסנן. וגם רשימה ריקה תיתן ZeroDivisionError. כך נראית הבעיה השנייה.KeyError: 'rating': the docstring said "that have one" but the code doesn't filter. An empty list would also give ZeroDivisionError. That's the second problem.
AssertionErrorבקשה בלי מקרי קצה מקבלת קוד בלי מקרי קצה.A request with no edge cases gets code with no edge cases.AssertionError: the prompt never mentions: ['empty', 'missing', 'round']: מה שלא אמרתם, העוזר מנחש. כותבים את הכללים במפורש.AssertionError: the prompt never mentions: ['empty', 'missing', 'round']: whatever you didn't say, the assistant guesses. Spell out the rules.
AssertionErrorקוד שנראה נכון ונכשל רק במקרה מסוים.Code that looks right and fails only in one case.AssertionError: 1900: got True, expected False: שנה שמתחלקת ב-100 אינה מעוברת, אלא אם מתחלקת ב-400. רק בדיקת מקרי קצה חושפת את זה.AssertionError: 1900: got True, expected False: a year divisible by 100 isn't a leap year unless divisible by 400. Only edge-case checks expose this.
AssertionErrorמשנים את הבדיקה כדי שתתאים לקוד שהעוזר כתב.Changing the test to fit the code the assistant wrote.AssertionError: got 'hello,-world!': fix the code, not the test: הבדיקה היא ההחלטה שלכם על מה נכון. מבקשים מהעוזר לתקן את הקוד, ומדביקים לו את הכישלון.AssertionError: got 'hello,-world!': fix the code, not the test: the test is your decision about what's right. Ask the assistant to fix the code, and paste the failure to it.
AttributeErrorמריצים קוד עם מתודה שהעוזר המציא.Running code with a method the assistant invented.AttributeError: 'list' object has no attribute 'remove_all': אין כזו. לרשימה יש remove (מופע ראשון). dir(list) מראה את כל מה שקיים.AttributeError: 'list' object has no attribute 'remove_all': there's no such thing. Lists have remove (first occurrence). dir(list) shows everything that exists.
AssertionErrorעוזר מציע קוד עם f-string בתוך SQL.An assistant suggests code with an f-string inside SQL.AssertionError: injection found [('boss',)]: use ? placeholders: קוד שנוצר לא תמיד בטוח. מזהים את הדפוס ומבקשים גרסה עם ?.AssertionError: injection found [('boss',)]: use ? placeholders: generated code isn't always safe. Spot the pattern and ask for a version with ?.

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