importasyncio# Define a coroutineasyncdefgreet(name:str)->str:awaitasyncio.sleep(0.1)# simulate I/Oreturnf"Hello, {name}!"# Run from synchronous code — the standard entry pointresult=asyncio.run(greet("world"))print(result)# Hello, world!
importasyncio# Run multiple coroutines concurrently — gather() returns results in orderasyncdefmain():results=awaitasyncio.gather(fetch("https://example.com/a"),fetch("https://example.com/b"),fetch("https://example.com/c"),)# results is a list in the same order as the arguments# Create a task explicitly (fires immediately, doesn't need to be awaited right away)asyncdefmain():task=asyncio.create_task(long_operation())# Do other work here...result=awaittask# wait for it now# TaskGroup — structured concurrency (Python 3.11+)asyncdefmain():asyncwithasyncio.TaskGroup()astg:t1=tg.create_task(operation_one())t2=tg.create_task(operation_two())# Both tasks are guaranteed complete here# If any task raises, the group cancels the others and re-raises# Limit concurrency with a Semaphoresem=asyncio.Semaphore(10)# max 10 concurrentasyncdefbounded_fetch(url):asyncwithsem:returnawaitfetch(url)
importasyncio# Lock — mutual exclusionlock=asyncio.Lock()asyncdefsafe_increment(counter:list):asyncwithlock:counter[0]+=1# only one coroutine runs this at a time# Event — notify waitersevent=asyncio.Event()asyncdefwaiter():awaitevent.wait()print("Event fired!")asyncdefsetter():awaitasyncio.sleep(1)event.set()# Queue — producer/consumerqueue=asyncio.Queue(maxsize=100)asyncdefproducer():foriteminrange(10):awaitqueue.put(item)awaitqueue.put(None)# sentinelasyncdefconsumer():whileTrue:item=awaitqueue.get()ifitemisNone:breakprocess(item)queue.task_done()
importaiohttpimportaiofilesimportasyncio# Async HTTP GET with aiohttpasyncdeffetch(url:str)->str:asyncwithaiohttp.ClientSession()assession:asyncwithsession.get(url)asresponse:returnawaitresponse.text()# Reuse a session across requests (preferred in production)asyncdeffetch_many(urls:list[str])->list[str]:asyncwithaiohttp.ClientSession()assession:tasks=[fetch_with_session(session,url)forurlinurls]returnawaitasyncio.gather(*tasks)# Async file I/O with aiofilesasyncdefread_file(path:str)->str:asyncwithaiofiles.open(path,mode="r")asf:returnawaitf.read()# Async generatorasyncdefpaginated_results(api_url:str):page=1whileTrue:data=awaitfetch(f"{api_url}?page={page}")ifnotdata:breakyielddatapage+=1# Consume an async generatorasyncdefprocess_all():asyncforpageinpaginated_results("https://api.example.com/items"):process(page)
asyncdeffan_out_fan_in(items:list)->list:"""Process many items concurrently, collect all results."""tasks=[asyncio.create_task(process(item))foriteminitems]results=awaitasyncio.gather(*tasks)returnlist(results)
asyncdefworker_pool(jobs:list,n_workers:int=5):"""Process jobs with a fixed number of concurrent workers."""queue=asyncio.Queue()forjobinjobs:awaitqueue.put(job)asyncdefworker():whilenotqueue.empty():job=awaitqueue.get()awaitprocess(job)queue.task_done()workers=[asyncio.create_task(worker())for_inrange(n_workers)]awaitqueue.join()forwinworkers:w.cancel()
importasyncioasyncdefwith_retry(coro_func,*args,retries=3,base_delay=1.0):"""Call an async function, retrying with exponential backoff on failure."""forattemptinrange(retries):try:returnawaitcoro_func(*args)exceptExceptionase:ifattempt==retries-1:raisedelay=base_delay*(2**attempt)awaitasyncio.sleep(delay)