Lesson 49 / 49
Async Basics
Run I/O-bound work concurrently with async, await and asyncio without threads.
Why async?
async/await let a program work on other tasks while one is waiting — e.g. for a network response — instead of blocking everything.
A minimal example
An async def function is a coroutine. await pauses it at a slow operation; asyncio.run starts the whole thing.
import asyncio
async def fetch_data(name, delay):
print(f"{name}: starting")
await asyncio.sleep(delay) # simulate I/O wait
print(f"{name}: done")
async def main():
await asyncio.gather(
fetch_data("A", 2),
fetch_data("B", 1),
)
asyncio.run(main())
Output:
A: starting B: starting B: done A: done
Final quiz 1 of 8
Final quiz
Quick check: Which type is immutable?
- list
- dict
- tuple
- set
Answer
tuple — Tuples cannot be changed after creation.
Final quiz 2 of 8
Final quiz
Quick check: What does `[n*n for n in range(4)]` produce?
- [1, 4, 9, 16]
- [0, 1, 2, 3]
- [0, 2, 4, 6]
- [0, 1, 4, 9]
Answer
[0, 1, 4, 9] — range(4) yields 0..3 and each is squared.
Final quiz 3 of 8
Final quiz
Quick check: Why avoid `def f(x, items=[])`?
- The list is created once and shared across calls
- It is a syntax error
- It is slower
- It cannot be called
Answer
The list is created once and shared across calls — Mutable defaults persist between calls; use None or a factory.
Final quiz 4 of 8
Final quiz
Quick check: What does `with open(...) as f:` guarantee?
- The file is encrypted
- The file is closed even if an error occurs
- The file is created
- The file is read-only
Answer
The file is closed even if an error occurs — Context managers run cleanup automatically.
Final quiz 5 of 8
Final quiz
Quick check: What does `yield` do in a function?
- Ends the program
- Raises an exception
- Produces a value lazily and pauses the function
- Returns a list
Answer
Produces a value lazily and pauses the function — Generators resume where they paused on the next call.
Final quiz 6 of 8
Final quiz
Quick check: Which decorator creates an alternate constructor?
- @staticmethod
- @property
- @dataclass
- @classmethod
Answer
@classmethod — A classmethod receives cls and can return a new instance.
Final quiz 7 of 8
Final quiz
Quick check: Which keyword starts a coroutine?
- async def
- yield def
- lambda
- class
Answer
async def — `async def` defines a coroutine you can await.
Final quiz 8 of 8
Final quiz
Quick check: Which tool isolates a project's packages?
- os
- venv
- sys
- math
Answer
venv — A virtual environment keeps dependencies per project.