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

חזרה למפגשBack
PythonPython

Dataclasses ו-type hintsDataclasses & type hints

מפגש 18: @dataclass, רמזי טיפוסים ובדיקה עם mypy.Session 18: @dataclass, type hints and checking with mypy.

מה נעשה היוםToday's plan

  • רמזיםHints
  • טיפוסיםTypes
  • dataclassdataclass
  • ברירות מחדלDefaults
  • אפשרויותOptions
  • mypymypy
נושאTopic 1

רמזיםHints

רמזי טיפוסType hints

  • def f(title: str, pages: int) -> str:def f(title: str, pages: int) -> str:
  • פייתון לא אוכפת אותםPython doesn't enforce them
  • העורך משלים ומזהירThe editor completes and warns
שאלה לכיתהQuestion for the class

מה ידפיס הקוד?What will this print?

python
def label(title: str, pages: int) -> str:
    return f"{title} ({pages} pages)"

print(label("Dune", 412))
print(label("Dune", "lots"))
print(label.__annotations__)

    רמזיםHints

    hints.py
    def label(title: str, pages: int) -> str:
        return f"{title} ({pages} pages)"
    
    print(label("Dune", 412))
    print(label("Dune", "lots"))
    print(label.__annotations__)
    פלטOutput
    Dune (412 pages)
    Dune (lots pages)
    {'title': <class 'str'>, 'pages': <class 'int'>, 'return': <class 'str'>}

    אנלוגיהAnalogy

    רמז טיפוס הוא כמו שלט "רק לאופניים" על שביל: הוא לא חוסם מכוניות פיזית, אבל כולם יודעים מה הכוונה, ומצלמה (mypy) תתפוס מי שעבר.A type hint is like a "bikes only" sign on a path: it doesn't physically block cars, but everyone knows the intent, and a camera (mypy) catches offenders.
    נושאTopic 2

    טיפוסיםTypes

    טיפוסים נפוציםCommon types

    • list[str], dict[str, int]list[str], dict[str, int]
    • `str | None`: אולי כלום`str | None`: maybe nothing
    • tuple[int, int]tuple[int, int]

    אנלוגיהAnalogy

    str | None הוא כמו קופסה שעליה כתוב "אולי יש פה עוגה": לפני שנוגסים, פותחים ובודקים.str | None is like a box labelled "there might be cake inside": before biting, open it and check.

    טעות נפוצהCommon mistake

    type_demo.py
    def total(nums: list(int)) -> int:
        return sum(nums)
    מה Python עונהWhat Python says
    TypeError: 'type' object is not iterable
    TypeError: 'type' object is not iterable: ברמזים משתמשים בסוגריים מרובעים: list[int].TypeError: 'type' object is not iterable: hints use square brackets: list[int].
    נושאTopic 3

    dataclassdataclass

    @dataclass@dataclass

    • שדות עם רמזים במקום __init__Fields with hints instead of __init__
    • __repr__ ו-__eq__ בחינם__repr__ and __eq__ for free
    • דקורטור @ מעל המחלקהA decorator @ above the class

    אנלוגיהAnalogy

    dataclass הוא כמו טופס מוכן: במקום לצייר טבלה ולכתוב כותרות בכל פעם, ממלאים רק את שמות השדות.A dataclass is like a ready-made form: instead of drawing the table and headings each time, you just fill in field names.
    נושאTopic 4

    ברירות מחדלDefaults

    ברירות מחדל ו-fieldDefaults and field

    • read: int = 0read: int = 0
    • רשימה כברירת מחדל: field(default_factory=list)A list default: field(default_factory=list)
    • שדות עם ברירת מחדל באים בסוףFields with defaults come last

    אנלוגיהAnalogy

    default_factory הוא כמו לתת לכל ילד מחברת חדשה, במקום מחברת אחת שכל הכיתה כותבת בה.default_factory is like giving every child a new notebook, instead of one notebook the whole class writes in.

    טעות נפוצהCommon mistake

    defaults.py
    from dataclasses import dataclass
    
    @dataclass
    class Book:
        title: str
        tags: list = []
    מה Python עונהWhat Python says
    ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory
    ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory: dataclass מגינה עלינו מהבאג הזה. משתמשים ב-field(default_factory=list).ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory: dataclass protects us from this bug. Use field(default_factory=list).
    נושאTopic 5

    אפשרויותOptions

    frozen, order ו-asdictfrozen, order and asdict

    • @dataclass(frozen=True): אי אפשר לשנות@dataclass(frozen=True): can't be changed
    • order=True: מיון לפי השדותorder=True: sort by the fields
    • asdict(b): חזרה למילוןasdict(b): back to a dict

    אנלוגיהAnalogy

    frozen הוא כמו תעודה למינציה: אפשר לקרוא ולהעתיק, אבל לא למחוק ולכתוב מעל.frozen is like a laminated certificate: you can read and copy it, but not erase and write over it.
    נושאTopic 6

    mypymypy

    mypy: בדיקה לפני הרצהmypy: checking before running

    • pip install mypypip install mypy
    • mypy shelf.py מוצא סתירותmypy shelf.py finds contradictions
    • ב-VS Code: הרחבת Pylance מסמנת בקו אדוםIn VS Code: the Pylance extension underlines in red

    אנלוגיהAnalogy

    mypy הוא כמו בודק איות לטיפוסים: מסמן את הטעות לפני שהמכתב נשלח.mypy is like a spell checker for types: it marks the mistake before the letter goes out.

    def f(title: str, pages: int) -> str:def f(title: str, pages: int) -> str:

    פייתון לא אוכפת אותםPython doesn't enforce them

    העורך משלים ומזהירThe editor completes and warns

    list[str], dict[str, int]list[str], dict[str, int]

    `str | None`: אולי כלום`str | None`: maybe nothing

    tuple[int, int]tuple[int, int]

    שדות עם רמזים במקום __init__Fields with hints instead of __init__

    __repr__ ו-__eq__ בחינם__repr__ and __eq__ for free

    דקורטור @ מעל המחלקהA decorator @ above the class

    read: int = 0read: int = 0

    רשימה כברירת מחדל: field(default_factory=list)A list default: field(default_factory=list)

    שדות עם ברירת מחדל באים בסוףFields with defaults come last

    @dataclass(frozen=True): אי אפשר לשנות@dataclass(frozen=True): can't be changed

    order=True: מיון לפי השדותorder=True: sort by the fields

    מה למדנוWhat we learned

    • def f(title: str, pages: int) -> str:def f(title: str, pages: int) -> str:
    • list[str], dict[str, int]list[str], dict[str, int]
    • שדות עם רמזים במקום __init__Fields with hints instead of __init__
    • read: int = 0read: int = 0
    • @dataclass(frozen=True): אי אפשר לשנות@dataclass(frozen=True): can't be changed
    • pip install mypypip install mypy

    עכשיו לתרגולNow, practice

    5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
    הערות מרצהSpeaker notes

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