Advanced Python
This chapter connects lazy iteration, higher-order behavior, deterministic resource cleanup, static analysis, and cooperative concurrency—the features that distinguish robust Python services from simple scripts.
- Explain Generators & iterators by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Decorators by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Context managers by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Type hints & mypy by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain asyncio basics by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For Advanced Python, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the language learning arc appropriate to this subject.
The problem this chapter solves
This chapter connects lazy iteration, higher-order behavior, deterministic resource cleanup, static analysis, and cooperative concurrency—the features that distinguish robust Python services from simple scripts.
The language lets a team express business rules quickly while retaining escape hatches for typing, concurrency, native extensions, packaging, and performance profiling.
Learning outcomes
- Explain Generators & iterators by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Decorators by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Context managers by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Type hints & mypy by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain asyncio basics by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Composition & performance by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
CPython compiles a module to bytecode, executes frames on a virtual machine, stores ordinary objects on a managed heap, and primarily reclaims them through reference counting with a cyclic garbage collector as a backstop. Names point to objects; assignment does not copy an object. The Global Interpreter Lock protects interpreter state in the standard CPython build, so threads are excellent for much I/O but not a general CPU-parallelism mechanism. In Advanced Python, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- Python executes the module top to bottom, creating imported names, constants, classes, and function objects before the example call runs.
- The call creates a frame, binds arguments to local names, and validates or normalizes each boundary value before deriving the result.
- Expressions evaluate left to right subject to Python's short-circuit rules; container operations allocate objects and retain references described in the memory section.
- A deliberate exception immediately begins stack unwinding; otherwise
returnpasses the result reference to the caller and the frame becomes collectible when no suspended work retains it. - The final print or assertion exposes the observable value, and edge-case tests repeat the same trace with empty, invalid, duplicate, or worst-shape input.
Memory and performance lens
A local name lives in a frame's fast-locals storage, while the referenced object normally lives on the heap. Immutable objects may be shared or interned. Containers store references, not embedded copies. Generators and coroutines preserve suspended frames, so retained locals stay alive until completion or close(). For Advanced Python, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Advanced Python, measure allocation count, retained-object size, iterator materialization, CPU profile, file/network call count, and execution time on representative input rather than optimizing from source-code appearance.
1. Generators & iterators
The Generators & iterators unit begins with __iter__ and __next__ protocol: An iterator produces one item at a time; a generator is an iterator whose suspended function frame resumes around yield. Use lazy iteration for streams or large datasets that do not need random access. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Generators & iterators
| Concept | Meaning | Engineering decision |
|---|---|---|
| __iter__ and __next__ protocol | An iterator produces one item at a time; a generator is an iterator whose suspended function frame resumes around yield. | Use lazy iteration for streams or large datasets that do not need random access. |
| yield keyword and generator functions | An iterator produces one item at a time; a generator is an iterator whose suspended function frame resumes around yield. | Use lazy iteration for streams or large datasets that do not need random access. |
| generator expressions | An iterator produces one item at a time; a generator is an iterator whose suspended function frame resumes around yield. | Use lazy iteration for streams or large datasets that do not need random access. |
| yield from for delegation | An iterator produces one item at a time; a generator is an iterator whose suspended function frame resumes around yield. | Use lazy iteration for streams or large datasets that do not need random access. |
| lazy CSV reader example | An iterator produces one item at a time; a generator is an iterator whose suspended function frame resumes around yield. | Use lazy iteration for streams or large datasets that do not need random access. |
What the runtime actually does: Generators & iterators
__iter__ and __next__ protocol. iter() obtains an iterator and repeated next() calls either yield a value or raise StopIteration. A generator preserves its instruction pointer, locals, and exception state.
yield keyword and generator functions. iter() obtains an iterator and repeated next() calls either yield a value or raise StopIteration. A generator preserves its instruction pointer, locals, and exception state.
generator expressions. iter() obtains an iterator and repeated next() calls either yield a value or raise StopIteration. A generator preserves its instruction pointer, locals, and exception state.
yield from for delegation. iter() obtains an iterator and repeated next() calls either yield a value or raise StopIteration. A generator preserves its instruction pointer, locals, and exception state.
lazy CSV reader example. iter() obtains an iterator and repeated next() calls either yield a value or raise StopIteration. A generator preserves its instruction pointer, locals, and exception state.
Read these as one system: __iter__ and __next__ protocol establishes the starting contract, yield keyword and generator functions changes how that contract is executed or represented, and lazy CSV reader example exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Generators & iterators
1class Writer(Protocol):2 def write(self, data: bytes) -> int: ...This Generators & iterators slice makes __iter__ and __next__ protocol observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward lazy CSV reader example, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Generators & iterators
| Risk | Why it matters |
|---|---|
| __iter__ and __next__ protocol | A consumed iterator is exhausted; converting it to a list defeats streaming and may exhaust memory. |
| yield keyword and generator functions | A consumed iterator is exhausted; converting it to a list defeats streaming and may exhaust memory. |
| generator expressions | A consumed iterator is exhausted; converting it to a list defeats streaming and may exhaust memory. |
| yield from for delegation | A consumed iterator is exhausted; converting it to a list defeats streaming and may exhaust memory. |
| lazy CSV reader example | A consumed iterator is exhausted; converting it to a list defeats streaming and may exhaust memory. |
Code it, observe it, explain it: Generators & iterators
- Foundation: implement or demonstrate __iter__ and __next__ protocol with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine __iter__ and __next__ protocol with yield keyword and generator functions. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for lazy CSV reader example. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Decorators
The Decorators unit begins with @functools.wraps: A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Decorators
| Concept | Meaning | Engineering decision |
|---|---|---|
| @functools.wraps | A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
| decorator factory pattern | A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
| class-based decorators | A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
| @timer/@retry/@cache real examples | A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
What the runtime actually does: Decorators
@functools.wraps. Decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references. wraps preserves metadata and the wrapped chain.
decorator factory pattern. Decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references. wraps preserves metadata and the wrapped chain.
class-based decorators. Decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references. wraps preserves metadata and the wrapped chain.
@timer/@retry/@cache real examples. Decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references. wraps preserves metadata and the wrapped chain.
Read these as one system: @functools.wraps establishes the starting contract, decorator factory pattern changes how that contract is executed or represented, and @timer/@retry/@cache real examples exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Mistakes that change program meaning: Decorators
| Risk | Why it matters |
|---|---|
| @functools.wraps | Keep retries bounded and restricted to transient, idempotent operations. |
| decorator factory pattern | Keep retries bounded and restricted to transient, idempotent operations. |
| class-based decorators | Keep retries bounded and restricted to transient, idempotent operations. |
| @timer/@retry/@cache real examples | Keep retries bounded and restricted to transient, idempotent operations. |
Code it, observe it, explain it: Decorators
- Foundation: implement or demonstrate @functools.wraps with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine @functools.wraps with decorator factory pattern. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for @timer/@retry/@cache real examples. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Context managers
The Context managers unit begins with class-based __enter__/__exit__: A context manager brackets a block with deterministic setup and cleanup. Use it for files, transactions, locks, temporary settings, and spans. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Context managers
| Concept | Meaning | Engineering decision |
|---|---|---|
| class-based __enter__/__exit__ | A context manager brackets a block with deterministic setup and cleanup. | Use it for files, transactions, locks, temporary settings, and spans. |
| @contextmanager from contextlib | A context manager brackets a block with deterministic setup and cleanup. | Use it for files, transactions, locks, temporary settings, and spans. |
| file locking / timer examples | A context manager brackets a block with deterministic setup and cleanup. | Use it for files, transactions, locks, temporary settings, and spans. |
What the runtime actually does: Context managers
class-based __enter__/__exit__. The with statement calls __enter__, runs the body, then calls __exit__ even during stack unwinding. __exit__ can suppress an exception only by returning truthy.
@contextmanager from contextlib. The with statement calls __enter__, runs the body, then calls __exit__ even during stack unwinding. __exit__ can suppress an exception only by returning truthy.
file locking / timer examples. The with statement calls __enter__, runs the body, then calls __exit__ even during stack unwinding. __exit__ can suppress an exception only by returning truthy.
Read these as one system: class-based __enter__/__exit__ establishes the starting contract, @contextmanager from contextlib changes how that contract is executed or represented, and file locking / timer examples exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Context managers
1@contextmanager2def resource():3 r = acquire()4 try: yield r5 finally: r.close()This Context managers slice makes class-based __enter__/__exit__ observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward file locking / timer examples, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Context managers
| Risk | Why it matters |
|---|---|
| class-based __enter__/__exit__ | Do not hide unexpected exceptions in __exit__; cleanup should be exception-safe. |
| @contextmanager from contextlib | Do not hide unexpected exceptions in __exit__; cleanup should be exception-safe. |
| file locking / timer examples | Do not hide unexpected exceptions in __exit__; cleanup should be exception-safe. |
Code it, observe it, explain it: Context managers
- Foundation: implement or demonstrate class-based __enter__/__exit__ with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine class-based __enter__/__exit__ with @contextmanager from contextlib. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for file locking / timer examples. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Type hints & mypy
The Type hints & mypy unit begins with Optional/Union/Literal/TypeVar: Type hints describe intended value relationships for tools without changing ordinary Python runtime dispatch. Annotate public boundaries and use precise unions or protocols. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Type hints & mypy
| Concept | Meaning | Engineering decision |
|---|---|---|
| Optional/Union/Literal/TypeVar | Type hints describe intended value relationships for tools without changing ordinary Python runtime dispatch. | Annotate public boundaries and use precise unions or protocols. |
| Generic classes | Type hints describe intended value relationships for tools without changing ordinary Python runtime dispatch. | Annotate public boundaries and use precise unions or protocols. |
| running mypy and fixing errors | Type hints describe intended value relationships for tools without changing ordinary Python runtime dispatch. | Annotate public boundaries and use precise unions or protocols. |
What the runtime actually does: Type hints & mypy
Optional/Union/Literal/TypeVar. A static checker builds a type model from annotations; generics preserve a relationship such as input and output element type. Runtime validation requires a separate library.
Generic classes. A static checker builds a type model from annotations; generics preserve a relationship such as input and output element type. Runtime validation requires a separate library.
running mypy and fixing errors. A static checker builds a type model from annotations; generics preserve a relationship such as input and output element type. Runtime validation requires a separate library.
Read these as one system: Optional/Union/Literal/TypeVar establishes the starting contract, Generic classes changes how that contract is executed or represented, and running mypy and fixing errors exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Mistakes that change program meaning: Type hints & mypy
| Risk | Why it matters | |
|---|---|---|
| Optional/Union/Literal/TypeVar | Optional[T] means `T \ | None`; it does not mean an optional function parameter. |
| Generic classes | Optional[T] means `T \ | None`; it does not mean an optional function parameter. |
| running mypy and fixing errors | Optional[T] means `T \ | None`; it does not mean an optional function parameter. |
Code it, observe it, explain it: Type hints & mypy
- Foundation: implement or demonstrate Optional/Union/Literal/TypeVar with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine Optional/Union/Literal/TypeVar with Generic classes. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for running mypy and fixing errors. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. asyncio basics
The asyncio basics unit begins with event loop and coroutines: Cooperative concurrency lets one task yield while it waits so another ready task can use the same thread. Use it for many independent I/O operations with async-compatible drivers. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: asyncio basics
| Concept | Meaning | Engineering decision |
|---|---|---|
| event loop and coroutines | Cooperative concurrency lets one task yield while it waits so another ready task can use the same thread. | Use it for many independent I/O operations with async-compatible drivers. |
| async/await syntax | Cooperative concurrency lets one task yield while it waits so another ready task can use the same thread. | Use it for many independent I/O operations with async-compatible drivers. |
| asyncio.gather() concurrency | Cooperative concurrency lets one task yield while it waits so another ready task can use the same thread. | Use it for many independent I/O operations with async-compatible drivers. |
| aiohttp async HTTP example | Cooperative concurrency lets one task yield while it waits so another ready task can use the same thread. | Use it for many independent I/O operations with async-compatible drivers. |
What the runtime actually does: asyncio basics
event loop and coroutines. Calling an async function creates a coroutine. await suspends only at an awaitable; the event loop schedules callbacks and resumes ready tasks. gather preserves input order but failure policy must be chosen.
async/await syntax. Calling an async function creates a coroutine. await suspends only at an awaitable; the event loop schedules callbacks and resumes ready tasks. gather preserves input order but failure policy must be chosen.
asyncio.gather() concurrency. Calling an async function creates a coroutine. await suspends only at an awaitable; the event loop schedules callbacks and resumes ready tasks. gather preserves input order but failure policy must be chosen.
aiohttp async HTTP example. Calling an async function creates a coroutine. await suspends only at an awaitable; the event loop schedules callbacks and resumes ready tasks. gather preserves input order but failure policy must be chosen.
Read these as one system: event loop and coroutines establishes the starting contract, async/await syntax changes how that contract is executed or represented, and aiohttp async HTTP example exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: asyncio basics
1results = await asyncio.gather(*(fetch(url) for url in urls))This asyncio basics slice makes event loop and coroutines observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward aiohttp async HTTP example, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: asyncio basics
| Risk | Why it matters |
|---|---|
| event loop and coroutines | A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. |
| async/await syntax | A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. |
| asyncio.gather() concurrency | A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. |
| aiohttp async HTTP example | A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. |
Code it, observe it, explain it: asyncio basics
- Foundation: implement or demonstrate event loop and coroutines with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine event loop and coroutines with async/await syntax. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for aiohttp async HTTP example. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
6. Composition & performance
The Composition & performance unit begins with decorator stacking order: A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Composition & performance
| Concept | Meaning | Engineering decision |
|---|---|---|
| decorator stacking order | A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
| list vs generator memory and latency | An iterator produces one item at a time; a generator is an iterator whose suspended function frame resumes around yield. | Use lazy iteration for streams or large datasets that do not need random access. |
| sequential await vs gather vs TaskGroup | Sequential awaits start one operation after the previous one finishes; asyncio.gather() schedules several awaitables together; TaskGroup adds structured lifetime and failure handling. | Use sequential awaits for real dependencies, gather() for simple independent result collection, and TaskGroup when sibling tasks must share an explicit scope. |
| cache key correctness and invalidation | A cache key must include every input that can change the answer, while invalidation defines when an authoritative change makes the stored answer unusable. | Document the source of truth, key schema, TTL, invalidation event, negative-cache policy, and stampede protection. |
What the runtime actually does: Composition & performance
decorator stacking order. Decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references. wraps preserves metadata and the wrapped chain.
list vs generator memory and latency. iter() obtains an iterator and repeated next() calls either yield a value or raise StopIteration. A generator preserves its instruction pointer, locals, and exception state.
sequential await vs gather vs TaskGroup. A sequential await suspends the current coroutine but does not create sibling work. gather() wraps coroutines as tasks and returns results in input order. A TaskGroup owns its child tasks, waits for all of them on exit, cancels siblings after an unhandled failure, and raises an exception group.
cache key correctness and invalidation. The application serializes a versioned key from identity, tenant, locale, permissions, query parameters, and other output-shaping inputs. Writes delete, replace, or version affected entries; TTL only bounds how long a missed invalidation remains stale.
Read these as one system: decorator stacking order establishes the starting contract, list vs generator memory and latency changes how that contract is executed or represented, and cache key correctness and invalidation exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Mistakes that change program meaning: Composition & performance
| Risk | Why it matters |
|---|---|
| decorator stacking order | Keep retries bounded and restricted to transient, idempotent operations. |
| list vs generator memory and latency | A consumed iterator is exhausted; converting it to a list defeats streaming and may exhaust memory. |
| sequential await vs gather vs TaskGroup | Creating concurrency for dependent work introduces races; using unbounded gather() can overload a remote service; ignoring exception groups loses individual failure causes. |
| cache key correctness and invalidation | Omitting tenant or authorization scope from a key can return one user's data to another; relying only on TTL can violate correctness for the entire expiry window. |
Code it, observe it, explain it: Composition & performance
- Foundation: implement or demonstrate decorator stacking order with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine decorator stacking order with list vs generator memory and latency. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for cache key correctness and invalidation. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1import asyncio2from collections.abc import AsyncIterator, Callable3from functools import wraps4from time import perf_counter5
6def timed(fn: Callable):7 @wraps(fn)8 async def wrapper(*args, **kwargs):9 started = perf_counter()10 try:11 return await fn(*args, **kwargs)12 finally:13 print(f"{fn.__name__}: {perf_counter() - started:.3f}s")14 return wrapper15
16async def values() -> AsyncIterator[int]:17 for value in range(3):18 await asyncio.sleep(0.01)19 yield value20
21@timed22async def main() -> list[int]:23 return [value * value async for value in values()]24
25print(asyncio.run(main()))Expected result
1main: approximately 0.030s2[0, 1, 4]Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | import asyncio | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 2 | from collections.abc import AsyncIterator, Callable | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 3 | from functools import wraps | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | from time import perf_counter | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 6 | def timed(fn: Callable): | Defines a function; its parameters form the explicit input boundary. |
| 7 | @wraps(fn) | Applies a decorator or framework annotation before the following definition is bound. |
| 8 | async def wrapper(args, *kwargs): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 9 | started = perf_counter() | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 10 | try: | Defines failure translation or cleanup that must run around the protected operation. |
| 11 | return await fn(args, *kwargs) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 12 | finally: | Defines failure translation or cleanup that must run around the protected operation. |
| 13 | print(f"{fn.__name__}: {perf_counter() - started:.3f}s") | Emits the example's observable output. |
| 14 | return wrapper | Returns the observable result to the caller and ends this invocation. |
| 16 | async def values() -> AsyncIterator[int]: | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 17 | for value in range(3): | Consumes the iterable one item at a time through the iterator protocol. |
| 18 | await asyncio.sleep(0.01) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 19 | yield value | Emits one lazy value and suspends the generator frame for a later resume. |
| 21 | @timed | Applies a decorator or framework annotation before the following definition is bound. |
| 22 | async def main() -> list[int]: | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 23 | return [value * value async for value in values()] | Returns the observable result to the caller and ends this invocation. |
| 25 | print(asyncio.run(main())) | Emits the example's observable output. |
Step-by-step execution
- Python executes the module top to bottom, creating imported names, constants, classes, and function objects before the example call runs.
- The call creates a frame, binds arguments to local names, and validates or normalizes each boundary value before deriving the result.
- Expressions evaluate left to right subject to Python's short-circuit rules; container operations allocate objects and retain references described in the memory section.
- A deliberate exception immediately begins stack unwinding; otherwise
returnpasses the result reference to the caller and the frame becomes collectible when no suspended work retains it. - The final print or assertion exposes the observable value, and edge-case tests repeat the same trace with empty, invalid, duplicate, or worst-shape input.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice | |
|---|---|---|---|
| Generators & iterators | A consumed iterator is exhausted; converting it to a list defeats streaming and may exhaust memory. | Use lazy iteration for streams or large datasets that do not need random access. | |
| Decorators | Keep retries bounded and restricted to transient, idempotent operations. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. | |
| Context managers | Do not hide unexpected exceptions in __exit__; cleanup should be exception-safe. | Use it for files, transactions, locks, temporary settings, and spans. | |
| Type hints & mypy | Optional[T] means `T \ | None`; it does not mean an optional function parameter. | Annotate public boundaries and use precise unions or protocols. |
| asyncio basics | A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. | Use it for many independent I/O operations with async-compatible drivers. | |
| Composition & performance | Keep retries bounded and restricted to transient, idempotent operations. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Async CLI Web Scraper project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Generators & iterators: __iter__ and __next__ protocol
- To do: Generators & iterators: yield keyword and generator functions
- To do: Generators & iterators: generator expressions
- To do: Generators & iterators: yield from for delegation
- To do: Generators & iterators: lazy CSV reader example
- To do: Decorators: @functools.wraps
- To do: Decorators: decorator factory pattern
- To do: Decorators: class-based decorators
- To do: Decorators: @timer/@retry/@cache real examples
- To do: Context managers: class-based __enter__/__exit__
- To do: Context managers: @contextmanager from contextlib
- To do: Context managers: file locking / timer examples
- To do: Type hints & mypy: Optional/Union/Literal/TypeVar
- To do: Type hints & mypy: Generic classes
- To do: Type hints & mypy: running mypy and fixing errors
- To do: asyncio basics: event loop and coroutines
- To do: asyncio basics: async/await syntax
- To do: asyncio basics: asyncio.gather() concurrency
- To do: asyncio basics: aiohttp async HTTP example
- To do: Composition & performance: decorator stacking order
- To do: Composition & performance: list vs generator memory and latency
- To do: Composition & performance: sequential await vs gather vs TaskGroup
- To do: Composition & performance: cache key correctness and invalidation
Quick revision
- Generators & iterators: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Decorators: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Context managers: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Type hints & mypy: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- asyncio basics: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Composition & performance: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?