C
Python/Async/Lesson 21

Introduction to Asynchronous Programming

1 hr·theory
Python

Introduction to Asynchronous Programming

🎯 After reading this lesson

After completing this lesson, you will be able to confidently do the following 3 things.

  • ✅ Explain why Python became the standard language for AI/data
  • ✅ Set up venv + requirements.txt with Python 3.x
  • ✅ Use the 4 built-in functions: print / input / type / dir

Keep these learning objectives as a checklist, and close the lesson once you can answer all of them.

async/await — Code + Execution Results

async def + await = process multiple tasks concurrently (single thread, efficient IO waiting). Standard for HTTP and database calls.


1. Synchronous vs Asynchronous — The Time Difference

python
import time

# ❌ Synchronous — Sequential execution (total 3 seconds)
def fetch():
    time.sleep(1)
    return "Done"

start = time.time()
results = [fetch() for _ in range(3)]
print(time.time() - start)        # 3.0 seconds
python
import asyncio

# ✅ Asynchronous — Concurrent execution (total 1 second)
async def fetch():
    await asyncio.sleep(1)        # Other tasks can run while waiting
    return "Done"

async def main():
    start = asyncio.get_event_loop().time()
    results = await asyncio.gather(
        fetch(), fetch(), fetch()
    )
    print(asyncio.get_event_loop().time() - start)    # 1.0 seconds

asyncio.run(main())

2. Key Keywords

KeywordMeaning
async defDefine an asynchronous function
awaitWait for an asynchronous result (other tasks can run in the meantime)
asyncio.run()Main entry point
asyncio.gather()Run multiple tasks concurrently

3. HTTP Calls (Production Use)

python
import asyncio
import aiohttp           # pip install aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = ["https://example.com", "https://python.org"]
    async with aiohttp.ClientSession() as session:
        results = await asyncio.gather(*[fetch(session, u) for u in urls])
        for r in results:
            print(len(r))

asyncio.run(main())

4. Common Mistakes

python
# ❌ Calling an async function directly — returns a coroutine (not executed)
result = fetch()                   # <coroutine object>

# ✅ await is required
result = await fetch()             # Actual execution

# ❌ Synchronous sleep — blocks other tasks
time.sleep(1)

# ✅ Asynchronous sleep
await asyncio.sleep(1)

One-Line Summary

async def + await + asyncio.gather() — speeds things up by N times where there is heavy IO waiting (HTTP, database).

💻 async/await Basics
import asyncio

# Define coroutine
async def say_hello(name, delay):
    await asyncio.sleep(delay)  # Asynchronous wait
    print(f"Hello, {name}!")
    return f"Done: {name}"

# Sequential execution (total 3 seconds)
async def sequential():
    await say_hello("A", 1)
    await say_hello("B", 1)
    await say_hello("C", 1)

# Concurrent execution (total 1 second)
async def concurrent():
    await asyncio.gather(
        say_hello("A", 1),
        say_hello("B", 1),
        say_hello("C", 1)
    )

# Execute
async def main():
    print("Sequential execution:")
    await sequential()
    
    print("\nConcurrent execution:")
    await concurrent()

# Main execution
asyncio.run(main())

# Synchronous vs Asynchronous comparison
# Synchronous: Request 1 complete → Request 2 start → Request 2 complete
# Asynchronous: Request 1 start → Request 2 start → Both complete

💡 Key Points

1. async def: define a coroutine function
2. await: wait for a coroutine to execute
3. asyncio.run(): run the event loop

⚠️ Note on asyncio.run(): Calling asyncio.run() inside an already-running event loop (e.g., Jupyter Notebook, inside FastAPI) will raise a RuntimeError. In those environments, use await coroutine directly or use the nest_asyncio library.

Asynchronous programming in Python is implemented using the asyncio library. Define coroutine functions with async def, and use await to wait for asynchronous operations. Use asyncio.gather() to run multiple coroutines concurrently. It is effective for I/O-bound tasks (HTTP, database, file). For CPU-bound tasks, use multiprocessing. aiohttp and httpx are asynchronous HTTP client libraries.

🐍 Try It Yourself — Introduction to Asynchronous Programming

Run the concepts above as actual code. The fastest way to learn is to change the values and observe the behavior yourself.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try asking AI like this

Once you understand the concepts in this lesson, you can give specific instructions to AI. Instead of a vague 'fix this,' you can make vocabulary-driven requests — that is where token savings begin.

  • 'Parallelize these synchronous requests calls using asyncio + httpx'
  • 'Add exception handling to this async code (asyncio.gather return_exceptions)'

Why this reduces tokens

Without understanding the concepts, you have to ask 'What is that?' again after receiving an AI response. That follow-up question is what consumes tokens. Learn the concept once, and the conversation ends in one round.

Read this first: Type Hinting
Introduction to Asynchronous Programming - Python