Bird
0
0

Which Python feature is used to create a lifespan context manager in FastAPI?

easy🧠 Conceptual Q2 of 15
FastAPI - Middleware and Hooks
Which Python feature is used to create a lifespan context manager in FastAPI?
ADecorator for route handlers
BClass inheritance from BaseModel
CSynchronous function returning a list
DAsync generator function with yield
Step-by-Step Solution
Solution:
  1. Step 1: Identify lifespan implementation

    FastAPI lifespan uses an async generator function that yields control during startup and shutdown.
  2. Step 2: Eliminate incorrect options

    Class inheritance, synchronous functions returning lists, and decorators for routes do not create lifespan managers.
  3. Final Answer:

    Async generator function with yield -> Option D
  4. Quick Check:

    Lifespan uses async generator with yield [OK]
Quick Trick: Lifespan uses async def with yield for startup/shutdown [OK]
Common Mistakes:
MISTAKES
  • Using sync functions without yield
  • Confusing with route decorators
  • Trying to subclass unrelated classes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes