0% found this document useful (0 votes)
2 views3 pages

Async Programming Notes

The document explains asynchronous programming in Python, highlighting its benefits for handling slow I/O operations. Key concepts include the use of 'async def' to declare asynchronous functions, 'await' to pause execution until a result is available, and the 'asyncio' library for managing asynchronous tasks. It also covers practical examples, exception handling, and when to use asynchronous versus synchronous programming.

Uploaded by

assamirzafar62
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Async Programming Notes

The document explains asynchronous programming in Python, highlighting its benefits for handling slow I/O operations. Key concepts include the use of 'async def' to declare asynchronous functions, 'await' to pause execution until a result is available, and the 'asyncio' library for managing asynchronous tasks. It also covers practical examples, exception handling, and when to use asynchronous versus synchronous programming.

Uploaded by

assamirzafar62
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Asynchronous Programming in Python

Why Async?

Normally, Python runs code line-by-line. Async lets Python do something else while waiting for slow I/O like
APIs, DBs, or files.

Key Concepts
async def - declares an async function
await - pauses until result
asyncio - built-in async library
[Link]() - runs the event loop

1. Synchronous vs Asynchronous

Synchronous Example
import time

def fetch_data():
[Link](3)
print("Data fetched")

print("Start")
fetch_data()
print("Done")

Asynchronous Example
import asyncio

async def fetch_data():


await [Link](3)
print("Data fetched")

async def main():


print("Start")
await fetch_data()
print("Done")

[Link](main())

2. Running Multiple Async Tasks Simultaneously


import asyncio

async def task(name, seconds):


print(f"{name} started")
Asynchronous Programming in Python

await [Link](seconds)
print(f"{name} finished after {seconds} sec")

async def main():


await [Link](
task("A", 2),
task("B", 3),
task("C", 1)
)

[Link](main())

3. await Only Works Inside async


async def say_hi():
return "Hi"

# ? await say_hi() (outside async won't work)

async def main():


result = await say_hi()
print(result)

[Link](main())

4. Coroutines vs Tasks
coro = fetch_data() # coroutine
asyncio.create_task(coro) # wraps coroutine as a task

5. Real-World Example: Web Requests


import asyncio

async def fake_api_call(url):


print(f"Fetching {url}...")
await [Link](2)
print(f"Finished {url}")

async def main():


urls = ["api/data1", "api/data2", "api/data3"]
tasks = [fake_api_call(url) for url in urls]
await [Link](*tasks)

[Link](main())

6. Mixing Async and Sync


async def myfunc():
await [Link](1)
Asynchronous Programming in Python

[Link](myfunc())

7. Exception Handling
async def risky():
raise ValueError("Uh oh!")

async def main():


try:
await risky()
except Exception as e:
print("Caught:", e)

[Link](main())

8. When to Use Async

Use async for: web scraping, APIs, DBs, file I/O


Use sync for: image processing, math, CPU-heavy tasks

9. [Link]() is the MVP


async def job(name, sec):
print(f"{name} started")
await [Link](sec)
print(f"{name} finished")

async def main():


await [Link](
job("A", 2),
job("B", 3),
job("C", 1)
)

# Total time ? 3 sec


[Link](main())

Summary Table
async def - declares a coroutine
await - pauses for async result
[Link]() - starts async loop
[Link]() - non-blocking wait
[Link]() - run multiple tasks together

You might also like