נבנה על ידי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.

או Ctrl+Por Ctrl+P

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

  • def f(title: str, pages: int) -> str:def f(title: str, pages: int) -> str:
  • פייתון לא אוכפת אותםPython doesn't enforce them
  • list[str], dict[str, int]list[str], dict[str, int]
  • `str | None`: אולי כלום`str | None`: maybe nothing
  • שדות עם רמזים במקום __init__Fields with hints instead of __init__
  • __repr__ ו-__eq__ בחינם__repr__ and __eq__ for free
  • read: int = 0read: int = 0
  • רשימה כברירת מחדל: field(default_factory=list)A list default: field(default_factory=list)
  • @dataclass(frozen=True): אי אפשר לשנות@dataclass(frozen=True): can't be changed

מונחיםTerms

  • רמז טיפוסtype hint: הערה בקוד שאומרת איזה טיפוס מצפים לו: pages: int. פייתון לא אוכפת אותה, אבל העורך וכלים כמו mypy כן משתמשים בה.A note in code saying which type is expected: pages: int. Python doesn't enforce it, but editors and tools like mypy use it.
  • dataclassdataclass: מחלקה שנוצרת עם @dataclass: פייתון כותבת לבד את __init__, __repr__ ו-__eq__ לפי השדות.A class made with @dataclass: Python writes __init__, __repr__ and __eq__ for you from the fields.
  • דקורטורdecorator: שורה שמתחילה ב-@ מעל פונקציה או מחלקה, ומוסיפה לה יכולות. @dataclass הוא דקורטור.A line starting with @ above a function or class that adds abilities to it. @dataclass is a decorator.
  • mypymypy: כלי שקורא את רמזי הטיפוס ומוצא סתירות בקוד בלי להריץ אותו. מתקינים עם pip install mypy.A tool that reads type hints and finds contradictions in code without running it. Install with pip install mypy.
  • Optional / NoneOptional / None: רמז שאומר "ערך מהסוג הזה או None": str | None.A hint meaning "a value of this type or None": str | None.

Cheatsheet

רמזיםHints
def label(title: str, pages: int) -> str:
    return f"{title} ({pages} pages)"

print(label("Dune", 412))
print(label("Dune", "lots"))
print(label.__annotations__)
טיפוסיםTypes
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:
dataclassdataclass
from dataclasses import dataclass

@dataclass
class Book:
    title: str
    author: str
    pages: int
אפשרויותOptions
from dataclasses import dataclass, asdict

@dataclass(frozen=True, order=True)
class Version:
    major: int
    minor: int
mypymypy
def percent(read: int, total: int) -> int:
    return round(read / total * 100)

print(percent(103, 412))
print(percent("103", 412))

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

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorחושבים שהרמז ממיר את הערך.Thinking the hint converts the value.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().
TypeErrorכותבים list(str) עם סוגריים עגולים.Writing list(str) with round brackets.TypeError: 'type' object is not iterable: ברמזים משתמשים בסוגריים מרובעים: list[int].TypeError: 'type' object is not iterable: hints use square brackets: list[int].
TypeErrorשוכחים את רמז הטיפוס, והשדה בכלל לא נוצר.Forgetting the type hint, so the field isn't created at all.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.
ValueErrorברירת מחדל של רשימה רגילה.A plain list as a default.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).
dataclasses.FrozenInstanceErrorמנסים לשנות אובייקט frozen.Trying to change a frozen object.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).
AssertionErrorמריצים mypy בלי שהוא מותקן בסביבה הפעילה.Running mypy when it isn't installed in the active environment.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.

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