async למתחיליםasync for beginners
async/await, asyncio.gather ומתי זה שווה.
async/await, asyncio.gather and when it is worth it.
01למה async?Why async?
כשמביאים פרטים על 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:
import time
def fetch(title):
time.sleep(0.3)
return f"{title}: ok"
start = time.perf_counter()
results = [fetch(t) for t in ["Dune", "Emma", "Matilda"]]
print(results)
print(f"{time.perf_counter() - start:.1f} seconds")['Dune: ok', 'Emma: ok', 'Matilda: ok'] 0.9 seconds
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.
חושבים ש-async יאיץ חישוב כבד.
Thinking async will speed up heavy computation.
import asyncio, time
async def crunch():
return sum(i * i for i in range(300_000))
async def main():
start = time.perf_counter()
await asyncio.gather(crunch(), crunch(), crunch())
return time.perf_counter() - start
once = time.perf_counter(); sum(i * i for i in range(300_000)); once = time.perf_counter() - once
took = asyncio.run(main())
assert took < once * 2, "three async crunches took about three times as long: async helps with waiting, not with computing"Traceback (most recent call last):
File "/Users/you/python-course/crunch.py", line 13, in <module>
assert took < once * 2, "three async crunches took about three times as long: async helps with waiting, not with computing"
^^^^^^^^^^^^^^^
AssertionError: three async crunches took about three times as long: async helps with waiting, not with computingAssertionError: three async crunches took about three times as long: ...: async מנצל זמן המתנה. חישוב לא מחכה לכלום, ולכן אין מה לנצל.AssertionError: three async crunches took about three times as long: ...: async uses waiting time. Computation doesn't wait for anything, so there's nothing to use.02async def ו-awaitasync def and await
פונקציה עם 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.
import asyncio
async def greet(name, delay):
print(f"start {name}")
await asyncio.sleep(delay)
print(f"done {name}")
return name.upper()
async def main():
result = await greet("Dune", 0.1)
print("got", result)
asyncio.run(main())start Dune done Dune got DUNE
await הוא כמו לשים שיחה בהמתנה: הקו לא נסגר, אבל בינתיים אפשר לענות לשיחה אחרת.
await is like putting a call on hold: the line stays open, but meanwhile you can answer another call.
קוראים לקורוטינה בלי await.
Calling a coroutine without await.
import asyncio
async def fetch():
return 42
async def main():
value = fetch()
return value + 1
asyncio.run(main())Traceback (most recent call last):
File "/Users/you/python-course/basics.py", line 10, in <module>
asyncio.run(main())
~~~~~~~~~~~^^^^^^^^
File "/usr/local/lib/python3.13/asyncio/runners.py", line 196, in run
return runner.run(main)
~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/asyncio/runners.py", line 119, in run
return self._loop.run_until_complete(task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/asyncio/base_events.py", line 726, in run_until_complete
return future.result()
~~~~~~~~~~~~~^^
File "/Users/you/python-course/basics.py", line 8, in main
return value + 1
~~~~~~^~~
TypeError: unsupported operand type(s) for +: 'coroutine' and 'int'
<sys>:0: RuntimeWarning: coroutine 'fetch' was never awaitedTypeError: unsupported operand type(s) for +: 'coroutine' and 'int': בלי await מקבלים "הבטחה" לתוצאה, לא את התוצאה. כותבים await fetch().TypeError: unsupported operand type(s) for +: 'coroutine' and 'int': without await you get a "promise" of a result, not the result. Write await fetch().yield נותן ערך אחד ומחכה. זה הבסיס של קוד אסינכרוני.
yield gives one value and waits. That's the base of async code.
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print("tick", x)tick 3 tick 2 tick 1
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03gather: כולם ביחדgather: all together
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.
import asyncio
import time
async def fetch(title, delay):
await asyncio.sleep(delay)
print("finished", title)
return f"{title}: ok"
async def main():
start = time.perf_counter()
results = await asyncio.gather(fetch("Dune", 0.3), fetch("Emma", 0.1), fetch("Matilda", 0.2))
print(results)
print(f"{time.perf_counter() - start:.1f} seconds")
asyncio.run(main())finished Emma finished Matilda finished Dune ['Dune: ok', 'Emma: ok', 'Matilda: ok'] 0.3 seconds
gather הוא כמו להזמין שלוש מנות במסעדה: כולן מתבשלות באותו זמן, והמלצר מביא אותן לפי הסדר שהזמנתם.
gather is like ordering three dishes: they all cook at the same time, and the waiter brings them in the order you ordered.
משתמשים ב-time.sleep בתוך קורוטינה.
Using time.sleep inside a coroutine.
import asyncio, time
async def fetch():
time.sleep(0.2)
async def main():
start = time.perf_counter()
await asyncio.gather(fetch(), fetch(), fetch())
took = time.perf_counter() - start
assert took < 0.4, f"took {took:.1f}s: time.sleep blocked the whole event loop"
asyncio.run(main())Traceback (most recent call last):
File "/Users/you/python-course/gather.py", line 12, in <module>
asyncio.run(main())
~~~~~~~~~~~^^^^^^^^
File "/usr/local/lib/python3.13/asyncio/runners.py", line 196, in run
return runner.run(main)
~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/asyncio/runners.py", line 119, in run
return self._loop.run_until_complete(task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/asyncio/base_events.py", line 726, in run_until_complete
return future.result()
~~~~~~~~~~~~~^^
File "/Users/you/python-course/gather.py", line 10, in main
assert took < 0.4, f"took {took:.1f}s: time.sleep blocked the whole event loop"
^^^^^^^^^^
AssertionError: took 0.6s: time.sleep blocked the whole event loopAssertionError: took 0.6s: time.sleep blocked the whole event loop: time.sleep לא אומר ללולאה שהוא מחכה. משתמשים ב-await asyncio.sleep.AssertionError: took 0.6s: time.sleep blocked the whole event loop: time.sleep doesn't tell the loop it's waiting. Use await asyncio.sleep.04Tasks ו-TaskGroupTasks and TaskGroup
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.
import asyncio
async def download(title, seconds):
await asyncio.sleep(seconds)
return len(title) * 100
async def main():
async with asyncio.TaskGroup() as tg:
tasks = {t: tg.create_task(download(t, 0.1)) for t in ["Dune", "Emma", "The Hobbit"]}
print("all started, waiting...")
for title, task in tasks.items():
print(title, task.result())
asyncio.run(main())all started, waiting... Dune 400 Emma 400 The Hobbit 1000
TaskGroup הוא כמו מדריך טיול שסופר את כל הילדים לפני שהאוטובוס יוצא: אף אחד לא נשאר מאחור.
A TaskGroup is like a trip leader counting every child before the bus leaves: nobody is left behind.
משימה שנכשלת בתוך TaskGroup.
A task that fails inside a TaskGroup.
import asyncio
async def ok():
await asyncio.sleep(0.1)
async def broken():
raise ValueError("bad ISBN")
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(ok())
tg.create_task(broken())
asyncio.run(main()) + Exception Group Traceback (most recent call last):
| File "/Users/you/python-course/tasks.py", line 14, in <module>
| asyncio.run(main())
| ~~~~~~~~~~~^^^^^^^^
| File "/usr/local/lib/python3.13/asyncio/runners.py", line 196, in run
| return runner.run(main)
| ~~~~~~~~~~^^^^^^
| File "/usr/local/lib/python3.13/asyncio/runners.py", line 119, in run
| return self._loop.run_until_complete(task)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
| File "/usr/local/lib/python3.13/asyncio/base_events.py", line 726, in run_until_complete
| return future.result()
| ~~~~~~~~~~~~~^^
| File "/Users/you/python-course/tasks.py", line 10, in main
| async with asyncio.TaskGroup() as tg:
| ~~~~~~~~~~~~~~~~~^^
| File "/usr/local/lib/python3.13/asyncio/taskgroups.py", line 71, in __aexit__
| return await self._aexit(et, exc)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
| File "/usr/local/lib/python3.13/asyncio/taskgroups.py", line 173, in _aexit
| raise BaseExceptionGroup(
| ...<2 lines>...
| ) from None
| ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "/Users/you/python-course/tasks.py", line 7, in broken
| raise ValueError("bad ISBN")
| ValueError: bad ISBN
+------------------------------------ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception): השגיאה עטופה בקבוצה כי כמה משימות יכולות להיכשל יחד. תופסים עם except* ValueError.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception): the error is wrapped in a group because several tasks may fail together. Catch it with except* ValueError.05Semaphore ו-timeoutSemaphores and timeouts
לשלוח 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.
import asyncio
active = 0
peak = 0
async def fetch(i, sem):
global active, peak
async with sem:
active += 1
peak = max(peak, active)
await asyncio.sleep(0.05)
active -= 1
return i
async def slow():
await asyncio.sleep(5)
async def main():
sem = asyncio.Semaphore(3)
results = await asyncio.gather(*(fetch(i, sem) for i in range(10)))
print(len(results), "done, at most", peak, "at once")
try:
await asyncio.wait_for(slow(), timeout=0.1)
except TimeoutError:
print("gave up after 0.1 s")
asyncio.run(main())10 done, at most 3 at once gave up after 0.1 s
Semaphore הוא כמו מספר קופות פתוחות בסופר: יכול להיות תור ארוך, אבל רק שלושה לקוחות משלמים באותו רגע.
A Semaphore is like the number of open checkouts: the queue can be long, but only three customers pay at any moment.
יוצרים Semaphore חדש בכל קריאה, ואז הוא לא מגביל כלום.
Creating a new Semaphore in every call, so it limits nothing.
import asyncio
active = peak = 0
async def fetch():
global active, peak
async with asyncio.Semaphore(2):
active += 1; peak = max(peak, active)
await asyncio.sleep(0.05)
active -= 1
async def main():
await asyncio.gather(*(fetch() for _ in range(6)))
assert peak <= 2, f"{peak} ran at once: every call had its own semaphore"
asyncio.run(main())Traceback (most recent call last):
File "/Users/you/python-course/limits.py", line 15, in <module>
asyncio.run(main())
~~~~~~~~~~~^^^^^^^^
File "/usr/local/lib/python3.13/asyncio/runners.py", line 196, in run
return runner.run(main)
~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/asyncio/runners.py", line 119, in run
return self._loop.run_until_complete(task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/asyncio/base_events.py", line 726, in run_until_complete
return future.result()
~~~~~~~~~~~~~^^
File "/Users/you/python-course/limits.py", line 13, in main
assert peak <= 2, f"{peak} ran at once: every call had its own semaphore"
^^^^^^^^^
AssertionError: 6 ran at once: every call had its own semaphoreAssertionError: 6 ran at once: every call had its own semaphore: Semaphore צריך להיות משותף. יוצרים אחד ב-main ומעבירים אותו.AssertionError: 6 ran at once: every call had its own semaphore: a Semaphore must be shared. Create one in main and pass it along.06בקשות רשת אמיתיותReal network requests
ספריית 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:
import asyncio
import httpx
async def book(client, isbn):
r = await client.get(f"https://openlibrary.org/isbn/{isbn}.json", timeout=10)
r.raise_for_status()
return r.json()["title"]
async def main():
isbns = ["9780441172719", "9780141439587", "9780156012195"]
async with httpx.AsyncClient() as client:
titles = await asyncio.gather(*(book(client, i) for i in isbns))
print(titles)
asyncio.run(main())import asyncio
import time
def old_blocking_fetch(title):
time.sleep(0.2)
return title.lower()
async def main():
start = time.perf_counter()
out = await asyncio.gather(*(asyncio.to_thread(old_blocking_fetch, t) for t in ["Dune", "Emma", "Matilda"]))
print(out, f"{time.perf_counter() - start:.1f} s")
asyncio.run(main())['dune', 'emma', 'matilda'] 0.2 s
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.
קוראים ל-asyncio.run מתוך קוד שכבר רץ בלולאה.
Calling asyncio.run from code already running in a loop.
import asyncio
async def inner():
return 1
async def main():
return asyncio.run(inner())
asyncio.run(main())Traceback (most recent call last):
File "/Users/you/python-course/nested.py", line 9, in <module>
asyncio.run(main())
~~~~~~~~~~~^^^^^^^^
File "/usr/local/lib/python3.13/asyncio/runners.py", line 196, in run
return runner.run(main)
~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/asyncio/runners.py", line 119, in run
return self._loop.run_until_complete(task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/asyncio/base_events.py", line 726, in run_until_complete
return future.result()
~~~~~~~~~~~~~^^
File "/Users/you/python-course/nested.py", line 7, in main
return asyncio.run(inner())
~~~~~~~~~~~^^^^^^^^^
File "/usr/local/lib/python3.13/asyncio/runners.py", line 192, in run
raise RuntimeError(
"asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop
<sys>:0: RuntimeWarning: coroutine 'inner' was never awaitedRuntimeError: asyncio.run() cannot be called from a running event loop: asyncio.run הוא רק נקודת הכניסה, פעם אחת. בתוך async כותבים await inner().RuntimeError: asyncio.run() cannot be called from a running event loop: asyncio.run is only the entry point, once. Inside async write await inner().סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.