async/await, asyncio.gather and when it is worth it.
כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.
חימום: 3 שאלותWarm-up: 3 questions
תרגיליםExercises
תרגילExercise 1
קורוטינה ראשונהA first coroutine
כתבו 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.
איך הפלט אמור להיראות?What should the output look like?
כתבו 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.
איך הפלט אמור להיראות?What should the output look like?
{'Dune': 4, 'Emma': 4, 'The Hobbit': 10}
main.py
רמזHint 1:results = await asyncio.gather(*(fake_fetch(t) for t in titles))results = await asyncio.gather(*(fake_fetch(t) for t in titles))
כתבו 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.
איך הפלט אמור להיראות?What should the output look like?
כתבו 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"].
איך הפלט אמור להיראות?What should the output look like?
4
main.py
רמזHint 1:Semaphore אחד שנוצר ב-crawl ומועבר.One Semaphore created in crawl and passed along.
רמזHint 2:בתוך async with sem: מגדילים, מחכים, ומקטינים.Inside async with sem: increase, wait, decrease.
מדף, צעד 30: פרטים לספרים רבים במקבילShelf, step 30: details for many books at once
פרויקט מלווהCompanion project
כתבו 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.
איך הפלט אמור להיראות?What should the output look like?
רמזHint 1:פונקציה פנימית one(isbn) עם Semaphore ו-try/except שמחזירה None לחסר.An inner one(isbn) with a Semaphore and try/except returning None for missing.
רמזHint 2:אחרי gather: מפרידים לפי None.After gather: split by None.
השתמשו ב-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.
איך הפלט אמור להיראות?What should the output look like?
4 ['a', 'b', 'c', 'd']
main.py
רמזHint 1:item = await q.get(), ו-if item is None: break.item = await q.get(), and if item is None: break.
רמזHint 2:מספר ה-None שווה למספר העובדים.The number of Nones equals the number of workers.
כתבו דקורטור 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.
איך הפלט אמור להיראות?What should the output look like?