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

חזרה למפגשBack
PythonPython

async למתחיליםasync for beginners

מפגש 30: async/await, asyncio.gather ומתי זה שווה.Session 30: async/await, asyncio.gather and when it is worth it.

מה נעשה היוםToday's plan

  • למהWhy
  • בסיסBasics
  • gathergather
  • TasksTasks
  • גבולותLimits
  • רשתNetwork
נושאTopic 1

למהWhy

למה async?Why async?

  • רוב הזמן תוכנית רשת מחכהA network program mostly waits
  • סדרתי: 3 × 1 שניה = 3 שניותSequential: 3 × 1 second = 3 seconds
  • async / אסינכרוני: מחכים לכולם ביחדasync / asynchronous: wait for all of them together

אנלוגיה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.
נושאTopic 2

בסיסBasics

async def ו-awaitasync def and await

  • async def יוצר קורוטינהasync def makes a coroutine
  • await = חכה, ותן לאחרים לרוץawait = wait, and let others run
  • asyncio.run(main()) מפעיל הכולasyncio.run(main()) starts it all

אנלוגיהAnalogy

await הוא כמו לשים שיחה בהמתנה: הקו לא נסגר, אבל בינתיים אפשר לענות לשיחה אחרת.await is like putting a call on hold: the line stays open, but meanwhile you can answer another call.
נושאTopic 3

gathergather

gather: כולם ביחדgather: all together

  • await asyncio.gather(a(), b(), c())await asyncio.gather(a(), b(), c())
  • התוצאות חוזרות באותו סדרResults come back in the same order
  • הזמן הכולל ≈ הארוכה ביותרTotal time ≈ the longest one

אנלוגיה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.
נושא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

אנלוגיהAnalogy

TaskGroup הוא כמו מדריך טיול שסופר את כל הילדים לפני שהאוטובוס יוצא: אף אחד לא נשאר מאחור.A TaskGroup is like a trip leader counting every child before the bus leaves: nobody is left behind.
נושאTopic 5

גבולותLimits

Semaphore ו-timeoutSemaphores and timeouts

  • `asyncio.Semaphore(3)`: עד 3 ביחד`asyncio.Semaphore(3)`: up to 3 together
  • asyncio.wait_for(coro, 1) → TimeoutErrorasyncio.wait_for(coro, 1) → TimeoutError
  • מנומס לשרת, מגן על התוכניתPolite to the server, safe for the program

אנלוגיהAnalogy

Semaphore הוא כמו מספר קופות פתוחות בסופר: יכול להיות תור ארוך, אבל רק שלושה לקוחות משלמים באותו רגע.A Semaphore is like the number of open checkouts: the queue can be long, but only three customers pay at any moment.
נושא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

אנלוגיה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.

רוב הזמן תוכנית רשת מחכהA network program mostly waits

סדרתי: 3 × 1 שניה = 3 שניותSequential: 3 × 1 second = 3 seconds

async / אסינכרוני: מחכים לכולם ביחדasync / asynchronous: wait for all of them together

async def יוצר קורוטינהasync def makes a coroutine

await = חכה, ותן לאחרים לרוץawait = wait, and let others run

asyncio.run(main()) מפעיל הכולasyncio.run(main()) starts it all

await asyncio.gather(a(), b(), c())await asyncio.gather(a(), b(), c())

התוצאות חוזרות באותו סדרResults come back in the same order

הזמן הכולל ≈ הארוכה ביותרTotal time ≈ the longest one

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

`asyncio.Semaphore(3)`: עד 3 ביחד`asyncio.Semaphore(3)`: up to 3 together

asyncio.wait_for(coro, 1) → TimeoutErrorasyncio.wait_for(coro, 1) → TimeoutError

מנומס לשרת, מגן על התוכניתPolite to the server, safe for the program

requests לא אסינכרוניתrequests is not async

httpx.AsyncClient (או aiohttp)httpx.AsyncClient (or aiohttp)

asyncio.to_thread לקוד ישןasyncio.to_thread for old code

מה למדנוWhat we learned

  • רוב הזמן תוכנית רשת מחכהA network program mostly waits
  • async def יוצר קורוטינהasync def makes a coroutine
  • await asyncio.gather(a(), b(), c())await asyncio.gather(a(), b(), c())
  • asyncio.create_task(coro()) מתחיל מידasyncio.create_task(coro()) starts right away
  • `asyncio.Semaphore(3)`: עד 3 ביחד`asyncio.Semaphore(3)`: up to 3 together
  • requests לא אסינכרוניתrequests is not async

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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