מפגש 30: async/await, asyncio.gather ומתי זה שווה.Session 30: async/await, asyncio.gather and when it is worth it.
async/await, asyncio.gather ומתי זה שווה. בסוף המפגש מוסיפים צעד לפרויקט המלווה.async/await, asyncio.gather and when it is worth it. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
למהWhy
בסיסBasics
gathergather
TasksTasks
גבולותLimits
רשתNetwork
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
נושאTopic 1
למהWhy
למה async?Why async?
רוב הזמן תוכנית רשת מחכהA network program mostly waits
כשמביאים פרטים על 50 ספרים מ-API, כל בקשה לוקחת חצי שנייה, ו-99% מהזמן המחשב פשוט מחכה לתשובה. קוד רגיל מחכה לכל אחת בתורה. async / אסינכרוני מאפשר לשלוח את כולן ולחכות להן יחד. כאן time.sleep מדמה בקשה איטית:Fetching details for 50 books from an API, each request takes half a second, and 99% of the time the computer just waits for the reply. Normal code waits for each in turn. async / asynchronous lets you send them all and wait for them together. Here time.sleep stands in for a slow request:
אנלוגיהAnalogy
async הוא כמו לבשל ארוחה: לא עומדים מול הקומקום עד שהוא רותח. שמים מים, ובזמן שהם מתחממים חותכים ירקות.async is like cooking dinner: you don't stand staring at the kettle until it boils. Put the water on, and chop vegetables while it heats.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
await = חכה, ותן לאחרים לרוץawait = wait, and let others run
asyncio.run(main()) מפעיל הכולasyncio.run(main()) starts it all
פונקציה עם async def היא קורוטינה. בתוכה, await asyncio.sleep(...) אומר ללולאת האירועים: "אני מחכה, תריצי מישהו אחר". נקודת הכניסה היא asyncio.run(main()). שימו לב: בתוך async משתמשים ב-asyncio.sleep, לא ב-time.sleep, שעוצר את הכול.A function with async def is a coroutine. Inside it, await asyncio.sleep(...) tells the event loop: "I'm waiting, run someone else". The entry point is asyncio.run(main()). Note: inside async use asyncio.sleep, not time.sleep, which freezes everything.
אנלוגיהAnalogy
await הוא כמו לשים שיחה בהמתנה: הקו לא נסגר, אבל בינתיים אפשר לענות לשיחה אחרת.await is like putting a call on hold: the line stays open, but meanwhile you can answer another call.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
התוצאות חוזרות באותו סדרResults come back in the same order
הזמן הכולל ≈ הארוכה ביותרTotal time ≈ the longest one
asyncio.gather מריץ כמה קורוטינות במקביל ומחזיר רשימת תוצאות, בסדר שבו נשלחו (גם אם סיימו בסדר אחר). אותה דוגמה מההתחלה, עם async: שלוש בקשות של 0.3 שניות לוקחות בערך 0.3 שניות ביחד.asyncio.gather runs several coroutines concurrently and returns a list of results, in the order sent (even if they finished in another order). The same example from the start, with async: three 0.3-second requests take about 0.3 seconds together.
אנלוגיהAnalogy
gather הוא כמו להזמין שלוש מנות במסעדה: כולן מתבשלות באותו זמן, והמלצר מביא אותן לפי הסדר שהזמנתם.gather is like ordering three dishes: they all cook at the same time, and the waiter brings them in the order you ordered.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 4
TasksTasks
Tasks ו-TaskGroupTasks and TaskGroup
asyncio.create_task(coro()) מתחיל מידasyncio.create_task(coro()) starts right away
async with asyncio.TaskGroup() as tg:async with asyncio.TaskGroup() as tg:
TaskGroup מחכה לכולם ומבטל אם יש שגיאהTaskGroup waits for all and cancels on error
Task הוא קורוטינה שהתחילה לרוץ ברקע, ואפשר להמשיך לעבוד ולחכות לה אחר כך. הדרך המודרנית (מפייתון 3.11) היא TaskGroup: כל ה-Tasks שנוצרו בתוך הבלוק נגמרים לפני שיוצאים ממנו, ואם אחד נכשל, השאר מבוטלים בצורה מסודרת.A Task is a coroutine that started running in the background, so you can keep working and await it later. The modern way (since Python 3.11) is TaskGroup: every Task created in the block finishes before you leave it, and if one fails, the rest are cancelled cleanly.
אנלוגיהAnalogy
TaskGroup הוא כמו מדריך טיול שסופר את כל הילדים לפני שהאוטובוס יוצא: אף אחד לא נשאר מאחור.A TaskGroup is like a trip leader counting every child before the bus leaves: nobody is left behind.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
מנומס לשרת, מגן על התוכניתPolite to the server, safe for the program
לשלוח 500 בקשות בבת אחת זה גם לא מנומס וגם עלול להיחסם (קוד 429). Semaphore מגביל: async with sem: נכנס רק אם יש מקום פנוי. ו-asyncio.wait_for מוותר על משימה שלוקחת יותר מדי זמן, בדיוק כמו timeout ב-requests.Sending 500 requests at once is impolite and may get you blocked (code 429). A Semaphore limits it: async with sem: enters only when a slot is free. And asyncio.wait_for gives up on a task that takes too long, just like a timeout in requests.
אנלוגיהAnalogy
Semaphore הוא כמו מספר קופות פתוחות בסופר: יכול להיות תור ארוך, אבל רק שלושה לקוחות משלמים באותו רגע.A Semaphore is like the number of open checkouts: the queue can be long, but only three customers pay at any moment.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 6
רשתNetwork
בקשות רשת אמיתיותReal network requests
requests לא אסינכרוניתrequests is not async
httpx.AsyncClient (או aiohttp)httpx.AsyncClient (or aiohttp)
asyncio.to_thread לקוד ישןasyncio.to_thread for old code
ספריית requests חוסמת, כמו time.sleep. לבקשות אסינכרוניות משתמשים ב-httpx עם AsyncClient (pip install httpx). אם יש פונקציה ישנה שחוסמת ואי אפשר לשנות, asyncio.to_thread מריץ אותה בצד בלי לעצור את הלולאה. כך נראה קוד אמיתי שמביא פרטים על כמה ספרים יחד:The requests library blocks, like time.sleep. For async requests use httpx with AsyncClient (pip install httpx). If you have an old blocking function you can't change, asyncio.to_thread runs it on the side without stopping the loop. Here's what real code fetching several books together looks like:
אנלוגיהAnalogy
to_thread הוא כמו לשלוח שליח לעמוד בתור בדואר במקומכם: אתם ממשיכים בעניינים, והוא חוזר עם החבילה.to_thread is like sending a runner to stand in the post-office queue for you: you carry on, and they come back with the parcel.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
רוב הזמן תוכנית רשת מחכהA network program mostly waits