async למתחיליםasync for beginners
async/await, asyncio.gather ומתי זה שווה.
async/await, asyncio.gather and when it is worth it.
קורוטינה ראשונהA first coroutine
תזכורת: מה ביקשוReminder: the task
כתבו async def double_later(n) שמחכה 0.01 שניות (asyncio.sleep) ומחזירה n×2, ו-async def main() שמדפיסה את await double_later(21). הריצו עם asyncio.run.
Write async def double_later(n) that waits 0.01 seconds (asyncio.sleep) and returns n×2, and async def main() printing await double_later(21). Run with asyncio.run.
הפתרון המלא והפלט שלוFull solution and its output
import asyncio
async def double_later(n):
await asyncio.sleep(0.01)
return n * 2
async def main():
print(await double_later(21))
asyncio.run(main())42
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
gathergather
תזכורת: מה ביקשוReminder: the task
כתבו async def fetch_all(titles) שמריצה במקביל fake_fetch(t) לכל כותרת (נתונה: מחכה 0.1 שנייה ומחזירה אורך הכותרת) ומחזירה מילון כותרת → תוצאה. 10 כותרות צריכות לקחת פחות מ-0.5 שנייה.
Write async def fetch_all(titles) running fake_fetch(t) for every title concurrently (given: waits 0.1 seconds and returns the title's length) and returning a dict title → result. 10 titles should take under 0.5 seconds.
הפתרון המלא והפלט שלוFull solution and its output
import asyncio
async def fake_fetch(title):
await asyncio.sleep(0.1)
return len(title)
async def fetch_all(titles):
results = await asyncio.gather(*(fake_fetch(t) for t in titles))
return dict(zip(titles, results))
print(asyncio.run(fetch_all(["Dune", "Emma", "The Hobbit"]))){'Dune': 4, 'Emma': 4, 'The Hobbit': 10}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
timeout לכל אחדA timeout for each
תזכורת: מה ביקשוReminder: the task
כתבו async def safe(coro, seconds) שמחזירה את התוצאה, או "timeout" אם עברו יותר מ-seconds. ואז async def main() שמריצה במקביל שלוש בקשות מדומות (slow(0.05), slow(0.5), slow(0.02)) עם timeout של 0.1 ומדפיסה את הרשימה.
Write async def safe(coro, seconds) returning the result, or "timeout" if more than seconds passed. Then async def main() running three fake requests concurrently (slow(0.05), slow(0.5), slow(0.02)) with a 0.1 timeout and printing the list.
הפתרון המלא והפלט שלוFull solution and its output
import asyncio
async def slow(seconds):
await asyncio.sleep(seconds)
return seconds
async def safe(coro, seconds):
try:
return await asyncio.wait_for(coro, seconds)
except TimeoutError:
return "timeout"
async def main():
print(await asyncio.gather(*(safe(slow(s), 0.1) for s in (0.05, 0.5, 0.02))))
asyncio.run(main())[0.05, 'timeout', 0.02]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
SemaphoreA Semaphore
תזכורת: מה ביקשוReminder: the task
כתבו async def crawl(urls, limit) שמריצה visit(url, sem, stats) לכל כתובת במקביל, אבל לא יותר מ-limit בבת אחת, ומחזירה את stats["peak"] (השיא של משימות פעילות). השלימו את visit כך שתעדכן stats["active"] ו-stats["peak"].
Write async def crawl(urls, limit) running visit(url, sem, stats) for every address concurrently, but no more than limit at once, returning stats["peak"] (the most active tasks at once). Complete visit so it updates stats["active"] and stats["peak"].
הפתרון המלא והפלט שלוFull solution and its output
import asyncio
async def visit(url, sem, stats):
async with sem:
stats["active"] += 1
stats["peak"] = max(stats["peak"], stats["active"])
await asyncio.sleep(0.02)
stats["active"] -= 1
async def crawl(urls, limit):
sem = asyncio.Semaphore(limit)
stats = {"active": 0, "peak": 0}
await asyncio.gather(*(visit(u, sem, stats) for u in urls))
return stats["peak"]
print(asyncio.run(crawl([f"/page/{i}" for i in range(12)], 4)))4
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 30: פרטים לספרים רבים במקבילShelf, step 30: details for many books at once
תזכורת: מה ביקשוReminder: the task
כתבו async def enrich(isbns, fetch, limit=3) ש-fetch(isbn) שלה היא קורוטינה שמחזירה מילון (או זורקת LookupError לספר שלא נמצא). היא מביאה את כולם במקביל (עד limit בבת אחת) ומחזירה (found, missing): רשימת מילונים בסדר הקלט, ורשימת ה-ISBN שלא נמצאו.
Write async def enrich(isbns, fetch, limit=3) whose fetch(isbn) is a coroutine returning a dict (or raising LookupError for a missing book). It fetches all concurrently (up to limit at once) and returns (found, missing): the dicts in input order, and the ISBNs not found.
הפתרון המלא והפלט שלוFull solution and its output
import asyncio
RECORDED = {"9780441172719": {"title": "Dune", "pages": 604}, "9780141439587": {"title": "Emma", "pages": 474}}
async def fake_fetch(isbn):
await asyncio.sleep(0.05)
if isbn not in RECORDED:
raise LookupError(isbn)
return RECORDED[isbn]
async def enrich(isbns, fetch, limit=3):
sem = asyncio.Semaphore(limit)
async def one(isbn):
async with sem:
try:
return await fetch(isbn)
except LookupError:
return None
results = await asyncio.gather(*(one(i) for i in isbns))
found = [r for r in results if r is not None]
missing = [i for i, r in zip(isbns, results) if r is None]
return found, missing
print(asyncio.run(enrich(["9780441172719", "0000000000", "9780141439587"], fake_fetch)))([{'title': 'Dune', 'pages': 604}, {'title': 'Emma', 'pages': 474}], ['0000000000'])יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מפיק וצרכןProducer and consumer
תזכורת: מה ביקשוReminder: the task
השתמשו ב-asyncio.Queue: producer(q, items) מכניס כל פריט ואז None לכל עובד כסימן סיום; worker(name, q, done) מוציא פריטים, "מעבד" (מחכה 0.01) ומוסיף ל-done את f"{name}:{item}" עד שמקבל None. main(items, workers=2) מריצה הכול ומחזירה את done ממוין.
Use asyncio.Queue: producer(q, items) puts every item and then a None per worker as a stop signal; worker(name, q, done) takes items, "processes" (waits 0.01) and appends f"{name}:{item}" to done until it gets None. main(items, workers=2) runs everything and returns done sorted.
הפתרון המלא והפלט שלוFull solution and its output
import asyncio
async def producer(q, items, workers):
for it in items:
await q.put(it)
for _ in range(workers):
await q.put(None)
async def worker(name, q, done):
while True:
item = await q.get()
if item is None:
break
await asyncio.sleep(0.01)
done.append(f"{name}:{item}")
async def main(items, workers=2):
q = asyncio.Queue()
done = []
await asyncio.gather(producer(q, items, workers), *(worker(f"w{i}", q, done) for i in range(workers)))
return sorted(done)
result = asyncio.run(main(["a", "b", "c", "d"]))
print(len(result), sorted(x.split(":")[1] for x in result))4 ['a', 'b', 'c', 'd']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ניסיון חוזר אסינכרוניAn async retry
תזכורת: מה ביקשוReminder: the task
כתבו דקורטור retry(times, delay) לקורוטינות: אם הפונקציה זורקת ConnectionError, מחכים delay (עם asyncio.sleep), ומנסים שוב עד times פעמים בסך הכול. אם כולן נכשלו, זורקים את האחרונה. שמרו את השם המקורי עם functools.wraps.
Write a retry(times, delay) decorator for coroutines: if the function raises ConnectionError, wait delay (with asyncio.sleep) and try again, up to times attempts in total. If all fail, raise the last. Keep the original name with functools.wraps.
הפתרון המלא והפלט שלוFull solution and its output
import asyncio
import functools
def retry(times, delay):
def deco(fn):
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
for attempt in range(times):
try:
return await fn(*args, **kwargs)
except ConnectionError:
if attempt == times - 1:
raise
await asyncio.sleep(delay)
return wrapper
return deco
calls = 0
@retry(times=3, delay=0.01)
async def flaky_fetch(isbn):
global calls
calls += 1
if calls < 3:
raise ConnectionError("network hiccup")
return f"{isbn}: ok"
print(asyncio.run(flaky_fetch("9780441172719")), calls, flaky_fetch.__name__)9780441172719: ok 3 flaky_fetch
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.