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

PythonPython
18
חלקPart 3: קוד נקי ו-OOPClean code & OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Dataclasses ו-type hintsDataclasses & type hints

@dataclass, רמזי טיפוסים ובדיקה עם mypy.

@dataclass, type hints and checking with mypy.

01רמזי טיפוסType hints

רמזי טיפוס אומרים לקורא (ולעורך) מה נכנס ומה יוצא. pages: int אומר "פה מצפים למספר שלם", ו--> str אומר מה הפונקציה מחזירה. חשוב לדעת: פייתון עצמה לא בודקת אותם בזמן ריצה. הם תיעוד חכם שכלים יודעים לקרוא.

Type hints tell the reader (and the editor) what goes in and what comes out. pages: int says "an integer is expected here", and -> str says what the function returns. Worth knowing: Python itself doesn't check them at runtime. They're smart documentation that tools can read.

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'>}
צפו בהרצה צעד אחר צעד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

רמז טיפוס הוא כמו שלט "רק לאופניים" על שביל: הוא לא חוסם מכוניות פיזית, אבל כולם יודעים מה הכוונה, ומצלמה (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.

טעות נפוצהCommon mistake

חושבים שהרמז ממיר את הערך.

Thinking the hint converts the value.

hints.py
def double(n: int) -> int:
    return n * 2

result = double("4")
assert result == 8, f"got {result!r}: hints don't convert anything"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/hints.py", line 5, in <module>
    assert result == 8, f"got {result!r}: hints don't convert anything"
           ^^^^^^^^^^^
AssertionError: got '44': hints don't convert anything
בעברית פשוטה: In plain words: AssertionError: got '44': hints don't convert anything: הרמז לא הפך את "4" למספר. ממירים בעצמנו עם int().AssertionError: got '44': hints don't convert anything: the hint didn't turn "4" into a number. Convert yourself with int().
צפו איפה זה נשבר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טיפוסים נפוציםCommon types

לאוספים כותבים גם מה בתוכם: list[str] היא רשימת מחרוזות, dict[str, int] ממפה מחרוזות למספרים. כשפונקציה מחזירה לפעמים None (כמו find), כותבים `Book | None`, וזו תזכורת לבדוק None לפני שימוש.

For collections you also write what's inside: list[str] is a list of strings, dict[str, int] maps strings to numbers. When a function sometimes returns None (like find), write `Book | None`, a reminder to check for None before use.

type_demo.py
def count_words(text: str) -> dict[str, int]:
    counts: dict[str, int] = {}
    for w in text.lower().split():
        counts[w] = counts.get(w, 0) + 1
    return counts

def first_long(words: list[str], n: int = 5) -> str | None:
    for w in words:
        if len(w) >= n:
            return w
    return None

print(count_words("to be or not to be"))
print(first_long(["a", "rose", "planet"]), first_long(["hi"]))
פלטOutput
{'to': 2, 'be': 2, 'or': 1, 'not': 1}
planet None
צפו בהרצה צעד אחר צעד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

str | None הוא כמו קופסה שעליה כתוב "אולי יש פה עוגה": לפני שנוגסים, פותחים ובודקים.

str | None is like a box labelled "there might be cake inside": before biting, open it and check.

טעות נפוצהCommon mistake

כותבים list(str) עם סוגריים עגולים.

Writing list(str) with round brackets.

type_demo.py
def total(nums: list(int)) -> int:
    return sum(nums)
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/type_demo.py", line 1, in <module>
    def total(nums: list(int)) -> int:
                    ~~~~^^^^^
TypeError: 'type' object is not iterable
בעברית פשוטה: In plain words: TypeError: 'type' object is not iterable: ברמזים משתמשים בסוגריים מרובעים: list[int].TypeError: 'type' object is not iterable: hints use square brackets: list[int].
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

03@dataclass@dataclass

מחלקות רבות הן בעיקר "מגירה לנתונים". dataclass חוסך את כל הקוד החוזר: כותבים את השדות עם רמזי טיפוס, ו-@dataclass (זה דקורטור) כותב בשבילנו __init__, __repr__ ו-__eq__. מתודות רגילות מוסיפים כרגיל.

Many classes are mostly "a drawer for data". dataclass saves all the repetitive code: write the fields with type hints, and @dataclass (that's a decorator) writes __init__, __repr__ and __eq__ for us. Regular methods are added as usual.

dc.py
from dataclasses import dataclass

@dataclass
class Book:
    title: str
    author: str
    pages: int

    def label(self) -> str:
        return f"{self.title} by {self.author}"

b = Book("Dune", "Frank Herbert", 412)
print(b)
print(b == Book("Dune", "Frank Herbert", 412))
print(b.label())
פלטOutput
Book(title='Dune', author='Frank Herbert', pages=412)
True
Dune by Frank Herbert
צפו בהרצה צעד אחר צעד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

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

A dataclass is like a ready-made form: instead of drawing the table and headings each time, you just fill in field names.

טעות נפוצהCommon mistake

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

Forgetting the type hint, so the field isn't created at all.

dc.py
from dataclasses import dataclass

@dataclass
class Book:
    title: str
    pages = 0

print(Book("Dune", 412))
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/dc.py", line 8, in <module>
    print(Book("Dune", 412))
          ~~~~^^^^^^^^^^^^^
TypeError: Book.__init__() takes 2 positional arguments but 3 were given
בעברית פשוטה: In plain words: TypeError: Book.__init__() takes 2 positional arguments but 3 were given: בלי : int פייתון לא רואה ב-pages שדה. כותבים pages: int = 0.TypeError: Book.__init__() takes 2 positional arguments but 3 were given: without : int Python doesn't treat pages as a field. Write pages: int = 0.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

dataclass כותבת לנו את __init__ ואת ההדפסה.

A dataclass writes __init__ and printing for us.

עוד דוגמה: ספר כ-dataclassOne more: a book as a dataclass
example.py
from dataclasses import dataclass

@dataclass
class Book:
    title: str
    pages: int = 100

b = Book("Dune", 412)
print(b)
print(b == Book("Dune", 412))
פלטOutput
Book(title='Dune', pages=412)
True
צפו בהרצה צעד אחר צעד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

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

שדה יכול לקבל ברירת מחדל: read: int = 0. לרשימה או מילון אסור לכתוב = [], כי אז כל האובייקטים היו חולקים את אותה רשימה. במקום זה: tags: list[str] = field(default_factory=list), שיוצר רשימה חדשה לכל אובייקט.

A field can have a default: read: int = 0. For a list or dict you mustn't write = [], because then every object would share one list. Instead: tags: list[str] = field(default_factory=list), which makes a fresh list per object.

ויזואלייזר זיכרוןMemory visualizerלכל ספר רשימה משלוEach book has its own list

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

פלטOutput

משתנים (frames)Variables (frames)

אובייקטים בזיכרוןObjects in memory

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

default_factory הוא כמו לתת לכל ילד מחברת חדשה, במקום מחברת אחת שכל הכיתה כותבת בה.

default_factory is like giving every child a new notebook, instead of one notebook the whole class writes in.

טעות נפוצהCommon mistake

ברירת מחדל של רשימה רגילה.

A plain list as a default.

defaults.py
from dataclasses import dataclass

@dataclass
class Book:
    title: str
    tags: list = []
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/defaults.py", line 3, in <module>
    @dataclass
     ^^^^^^^^^
  File "/usr/local/lib/python3.13/dataclasses.py", line 1354, in dataclass
    return wrap(cls)
  File "/usr/local/lib/python3.13/dataclasses.py", line 1344, in wrap
    return _process_class(cls, init, repr, eq, order, unsafe_hash,
                          frozen, match_args, kw_only, slots,
                          weakref_slot)
  File "/usr/local/lib/python3.13/dataclasses.py", line 1008, in _process_class
    cls_fields.append(_get_field(cls, name, type, kw_only))
                      ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/dataclasses.py", line 860, in _get_field
    raise ValueError(f'mutable default {type(f.default)} for field '
                     f'{f.name} is not allowed: use default_factory')
ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory
בעברית פשוטה: In plain words: 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).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

05frozen, order ו-asdictfrozen, order and asdict

ל-dataclass יש אפשרויות. frozen=True הופך את האובייקט לבלתי ניתן לשינוי, מצוין לערכים כמו נקודה או תאריך. order=True יוצר < שמשווה שדה אחרי שדה. asdict ממיר למילון, שימושי לשמירה ל-JSON במפגש 21.

Dataclass has options. frozen=True makes the object unchangeable, great for values like a point or a date. order=True creates < comparing field by field. asdict converts to a dict, handy for saving to JSON in session 21.

frozen.py
from dataclasses import dataclass, asdict

@dataclass(frozen=True, order=True)
class Version:
    major: int
    minor: int

vs = [Version(3, 12), Version(3, 9), Version(2, 7)]
print(sorted(vs))
print(max(vs), asdict(max(vs)))
פלטOutput
[Version(major=2, minor=7), Version(major=3, minor=9), Version(major=3, minor=12)]
Version(major=3, minor=12) {'major': 3, 'minor': 12}
צפו בהרצה צעד אחר צעד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

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

frozen is like a laminated certificate: you can read and copy it, but not erase and write over it.

טעות נפוצהCommon mistake

מנסים לשנות אובייקט frozen.

Trying to change a frozen object.

frozen.py
from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
p.x = 5
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/frozen.py", line 9, in <module>
    p.x = 5
    ^^^
  File "<string>", line 16, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'x'
בעברית פשוטה: In plain words: dataclasses.FrozenInstanceError: cannot assign to field 'x': זו בדיוק המטרה. ליצירת גרסה חדשה: dataclasses.replace(p, x=5).dataclasses.FrozenInstanceError: cannot assign to field 'x': that's the whole point. For a new version: dataclasses.replace(p, x=5).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

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

כאן הרמזים מתחילים לעבוד בשבילכם. mypy קורא את הקוד בלי להריץ ומחפש סתירות: מעבירים מחרוזת לפונקציה שמצפה למספר, או משתמשים בתוצאה שעלולה להיות None. ב-VS Code, Pylance עושה בדיקה דומה תוך כדי כתיבה.

Here the hints start working for you. mypy reads the code without running it and looks for contradictions: passing a string to a function that expects a number, or using a result that might be None. In VS Code, Pylance does a similar check as you type.

check_me.py
def percent(read: int, total: int) -> int:
    return round(read / total * 100)

print(percent(103, 412))
print(percent("103", 412))
מה Python עונהWhat Python says
25
Traceback (most recent call last):
  File "/Users/you/python-course/check_me.py", line 5, in <module>
    print(percent("103", 412))
          ~~~~~~~^^^^^^^^^^^^
  File "/Users/you/python-course/check_me.py", line 2, in percent
    return round(read / total * 100)
                 ~~~~~^~~~~~~
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Terminal
mypy check_me.py
פלט לדוגמהSample output
check_me.py:5: error: Argument 1 to "percent" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 1 source file)
אנלוגיה מהחייםReal-life analogy

mypy הוא כמו בודק איות לטיפוסים: מסמן את הטעות לפני שהמכתב נשלח.

mypy is like a spell checker for types: it marks the mistake before the letter goes out.

טעות נפוצהCommon mistake

מריצים mypy בלי שהוא מותקן בסביבה הפעילה.

Running mypy when it isn't installed in the active environment.

check.py
import importlib.util
assert importlib.util.find_spec("mypy_not_here") is not None, "mypy is not installed here: run pip install mypy inside the venv"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/check.py", line 2, in <module>
    assert importlib.util.find_spec("mypy_not_here") is not None, "mypy is not installed here: run pip install mypy inside the venv"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: mypy is not installed here: run pip install mypy inside the venv
בעברית פשוטה: In plain words: AssertionError: mypy is not installed here: ...: בטרמינל זה ייראה כ-command not found: mypy. מפעילים את ה-venv ומריצים pip install mypy.AssertionError: mypy is not installed here: ...: in the terminal it shows as command not found: mypy. Activate the venv and run pip install mypy.

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

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

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

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