5.10 contextlib (@contextmanager) (Week 5 • Advanced Python 3.12)
1. Core Concept & Internal Working
contextlib (@contextmanager) (Advanced Python 3.12) covers `from contextlib import contextmanager, suppress, ExitStack` generator-based context managers (`try: yield resource finally: cleanup()`). In production software engineering, it is used to Writing FastAPI `lifespan` startup/shutdown hooks and request-scoped DB session generators cleanly. Mastering its underlying execution rules and edge-case boundaries lets you write reliable, maintainable code.
2. Real-World Engineering Use Case
Writing FastAPI `lifespan` startup/shutdown hooks and request-scoped DB session generators cleanly.
3. Granular Subtopics Covered
- `from contextlib import contextmanager: Core foundation of contextlib (@contextmanager): Writing FastAPI `lifespan` startup/shutdown hooks and request-scoped DB session generators cleanly.
- Suppress: Master 'Suppress' inside contextlib (@contextmanager) across real-world inputs.
- ExitStack` generator-based context managers (`try: yield resource finally: cleanup()`): Master 'ExitStack` generator-based context managers (`try: yield resource finally: cleanup()`)' inside contextlib (@contextmanager) across real-world inputs.
- Production Pitfall Guard (contextlib (@contextmanager)): Prevent common defect: Omitting `try ... finally:` around `yield` inside `@contextmanager` — if the caller raises an exception, cleanup code after `yield` NEVER runs!
- Hands-On Verification (contextlib (@contextmanager)): Write a `@contextmanager` temporary working-directory switcher guaranteed to restore `cwd` via `try/finally`.
- contextlib (@contextmanager) — Interview Readiness: Explain behavior, trade-offs, and edge cases of contextlib (@contextmanager).
4. Reference Implementation
from contextlib import contextmanager
@contextmanager
def temp_feature_flag(flags: dict[str, bool], key: str):
prev = flags.get(key, False)
flags[key] = True
try:
yield flags
finally:
flags[key] = prev
cfg = {'beta': False}
with temp_feature_flag(cfg, 'beta'):
print('Inside:', cfg['beta'])
print('Outside:', cfg['beta'])
5. Common Mistakes to Avoid
- Omitting `try ... finally:` around `yield` inside `@contextmanager` — if the caller raises an exception, cleanup code after `yield` NEVER runs!
- Skipping boundary, null/empty, or error-state verification when implementing contextlib (@contextmanager).
- Pushing untested contextlib (@contextmanager) changes without clean naming and Git commit context.
6. Hands-On Exercise
Write a `@contextmanager` temporary working-directory switcher guaranteed to restore `cwd` via `try/finally`.
7. Technical Interview Checkpoints
- Q: What problem does contextlib (@contextmanager) solve in Advanced Python 3.12, and what fails if it is misused?
Key Focus: Writing FastAPI `lifespan` startup/shutdown hooks and request-scoped DB session generators cleanly. Guard against: Omitting `try ... finally:` around `yield` inside `@contextmanager` — if the caller raises an exception, cleanup code after `yield` NEVER runs! - Q: Explain the internal working of contextlib (@contextmanager) (`from contextlib import contextmanager, suppress, ExitStack` generator-based context managers (`try: yield resource finally: cleanup()`)).
Key Focus: Walk step-by-step through `from contextlib import contextmanager, suppress, ExitStack` generator-based context managers (`try: yield resource finally: cleanup()`) with a concrete code example. - Q: How did you apply and verify contextlib (@contextmanager) in your hands-on lab?
Key Focus: Write a `@contextmanager` temporary working-directory switcher guaranteed to restore `cwd` via `try/finally`.