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

PythonPython
30
חלקPart 5: בונים דבריםBuilding things כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

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

async/await, asyncio.gather ומתי זה שווה.

async/await, asyncio.gather and when it is worth it.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • רוב הזמן תוכנית רשת מחכהA network program mostly waits
  • סדרתי: 3 × 1 שניה = 3 שניותSequential: 3 × 1 second = 3 seconds
  • async def יוצר קורוטינהasync def makes a coroutine
  • await = חכה, ותן לאחרים לרוץawait = wait, and let others run
  • await asyncio.gather(a(), b(), c())await asyncio.gather(a(), b(), c())
  • התוצאות חוזרות באותו סדרResults come back in the same order
  • asyncio.create_task(coro()) מתחיל מידasyncio.create_task(coro()) starts right away
  • async with asyncio.TaskGroup() as tg:async with asyncio.TaskGroup() as tg:
  • `asyncio.Semaphore(3)`: עד 3 ביחד`asyncio.Semaphore(3)`: up to 3 together

מונחיםTerms

  • async / אסינכרוניasync / asynchronous: סגנון תכנות שבו בזמן שמחכים למשהו (רשת, דיסק), התוכנית עושה עבודה אחרת במקום לעמוד.A programming style where, while waiting for something (network, disk), the program does other work instead of standing still.
  • קורוטינהcoroutine: פונקציה שהוגדרה עם async def. קריאה אליה מחזירה אובייקט שצריך להריץ עם await או asyncio.run.A function defined with async def. Calling it returns an object you must run with await or asyncio.run.
  • awaitawait: "חכה לזה, ובינתיים תן לאחרים לרוץ". מותר רק בתוך async def."Wait for this, and meanwhile let others run". Allowed only inside async def.
  • לולאת אירועיםevent loop: המנגנון של asyncio שמחליט מי רץ עכשיו: מריץ קורוטינה עד await, ואז עובר לאחרת שמוכנה.asyncio's engine that decides who runs now: runs a coroutine until an await, then switches to another that's ready.
  • TaskTask: קורוטינה שתוזמנה לרוץ ברקע עם asyncio.create_task, ואפשר לחכות לה מאוחר יותר.A coroutine scheduled to run in the background with asyncio.create_task, to be awaited later.
  • מקביליות (concurrency)concurrency: כמה משימות מתקדמות באותו פרק זמן, גם אם רק אחת רצה בכל רגע.Several tasks making progress in the same period, even if only one runs at any instant.
  • SemaphoreSemaphore: מונה שמגביל כמה משימות רצות יחד, למשל לא יותר מ-3 בקשות לשרת בבת אחת.A counter that limits how many tasks run together, e.g. no more than 3 requests to a server at once.

Cheatsheet

למהWhy
import time

def fetch(title):
    time.sleep(0.3)
    return f"{title}: ok"

start = time.perf_counter()
בסיסBasics
import asyncio

async def greet(name, delay):
    print(f"start {name}")
    await asyncio.sleep(delay)
    print(f"done {name}")
    return name.upper()
gathergather
import asyncio
import time

async def fetch(title, delay):
    await asyncio.sleep(delay)
    print("finished", title)
    return f"{title}: ok"
TasksTasks
import asyncio

async def download(title, seconds):
    await asyncio.sleep(seconds)
    return len(title) * 100

async def main():
גבולותLimits
import asyncio

active = 0
peak = 0

async def fetch(i, sem):
    global active, peak
רשתNetwork
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"]

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorחושבים ש-async יאיץ חישוב כבד.Thinking async will speed up heavy computation.AssertionError: 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.
<sys>קוראים לקורוטינה בלי await.Calling a coroutine without await.TypeError: 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().
AssertionErrorמשתמשים ב-time.sleep בתוך קורוטינה.Using time.sleep inside a coroutine.AssertionError: 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.
+------------------------------------משימה שנכשלת בתוך TaskGroup.A task that fails inside a TaskGroup.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.
AssertionErrorיוצרים Semaphore חדש בכל קריאה, ואז הוא לא מגביל כלום.Creating a new Semaphore in every call, so it limits nothing.AssertionError: 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.
<sys>קוראים ל-asyncio.run מתוך קוד שכבר רץ בלולאה.Calling asyncio.run from code already running in a loop.RuntimeError: 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().

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