[Python] How is passing a generator to Depends make the generator act like a contextmanager?

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I was going through a tutorial on fast api and I came across something like below

    def get_db():
    try:
    db = SessionLocal()
    yield db
    finally:
    print("from finally block")
    db.close()


    @app.get("/")
    async def read_all(db: Session = Depends(get_db)):
    res = db.query(models.Todos).all()
    print("from endpoint")
    return res


    result

    INFO: 127.0.0.1:39088 - "GET /openapi.json HTTP/1.1" 200 OK
    from endpoint
    INFO: 127.0.0.1:39088 - "GET / HTTP/1.1" 200 OK
    from finally block



    why does Depends(get_db) seem to act like somekind of contextmanager?. the "from finally block" print statement does not get executed until the end of the read_all method

    doing something like


    class SomeDependency:
    def __enter__(self):
    print("entering")
    def __exit__(self, exc_type, exc_val, exc_tb):
    print("exited")

    def hello():
    try:
    yield SomeDependency()
    finally:
    print("yolo")

    if __name__ == "__main__":
    next(hello())


    the finally block gets executed immediately after the call to next.

    what why does the finally block of the get_db not execute immediately when passed to Depends?

    Continue reading...

Compartilhe esta Página