Context managers guarantee setup and teardown even when exceptions occur. __exit__(exc_type, exc, tb) runs on exit; returning True suppresses the exception, while returning False/None lets it propagate. In FastAPI, @asynccontextmanager lifespan initializes shared pools/clients before yield and closes them cleanly on shutdown.
Follow-up Interview Question · How can contextlib.ExitStack manage a dynamic number of context managers?