חלק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.
הנקודות החשובות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 freeread: 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.@dataclassis a decorator. - mypymypy: כלי שקורא את רמזי הטיפוס ומוצא סתירות בקוד בלי להריץ אותו. מתקינים עם
pip install mypy.A tool that reads type hints and finds contradictions in code without running it. Install withpip 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. |