נבנה על ידיBuilt by Ariel Yohimovich
def f(title: str, pages: int) -> str:def f(title: str, pages: int) -> str: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.def label(title: str, pages: int) -> str:
return f"{title} ({pages} pages)"
print(label("Dune", 412))
print(label("Dune", "lots"))
print(label.__annotations__)def label(title: str, pages: int) -> str:
return f"{title} ({pages} pages)"
print(label("Dune", 412))
print(label("Dune", "lots"))
print(label.__annotations__)Dune (412 pages)
Dune (lots pages)
{'title': <class 'str'>, 'pages': <class 'int'>, 'return': <class 'str'>}list[str], dict[str, int]list[str], dict[str, int]tuple[int, int]tuple[int, int]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.str | None הוא כמו קופסה שעליה כתוב "אולי יש פה עוגה": לפני שנוגסים, פותחים ובודקים.str | None is like a box labelled "there might be cake inside": before biting, open it and check.def total(nums: list(int)) -> int:
return sum(nums)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].list(str) עם סוגריים עגולים.Writing list(str) with round brackets.__init__Fields with hints instead of __init____repr__ ו-__eq__ בחינם__repr__ and __eq__ for free@ מעל המחלקהA decorator @ above the class@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.read: int = 0read: int = 0field(default_factory=list)A list default: field(default_factory=list)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.default_factory הוא כמו לתת לכל ילד מחברת חדשה, במקום מחברת אחת שכל הכיתה כותבת בה.default_factory is like giving every child a new notebook, instead of one notebook the whole class writes in.from dataclasses import dataclass
@dataclass
class Book:
title: str
tags: list = []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).@dataclass(frozen=True): אי אפשר לשנות@dataclass(frozen=True): can't be changedorder=True: מיון לפי השדותorder=True: sort by the fieldsasdict(b): חזרה למילוןasdict(b): back to a dictfrozen=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.pip install mypypip install mypymypy shelf.py מוצא סתירותmypy shelf.py finds contradictionsdef f(title: str, pages: int) -> str:def f(title: str, pages: int) -> str:list[str], dict[str, int]list[str], dict[str, int]tuple[int, int]tuple[int, int]__init__Fields with hints instead of __init____repr__ ו-__eq__ בחינם__repr__ and __eq__ for free@ מעל המחלקהA decorator @ above the classread: int = 0read: int = 0field(default_factory=list)A list default: field(default_factory=list)@dataclass(frozen=True): אי אפשר לשנות@dataclass(frozen=True): can't be changedorder=True: מיון לפי השדותorder=True: sort by the fieldsdef 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 changedpip install mypypip install mypyנבנה על ידיBuilt by Ariel Yohimovich