[Python] Returning await anext(gen) from function results in exception

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    While refactoring a middleware interceptor function, I moved this code for getting the db session:

    if get_async_session in request.app.dependency_overrides:
    get_session = request.app.dependency_overrides[get_async_session]
    db_session = get_session()
    else:
    get_session = get_async_session
    gen = get_session()
    db_session = await anext(gen)


    into a function:

    async def get_session_from_request_dependencies_or_generator(
    request: Request,
    ) -> AsyncSession:
    if get_async_session in request.app.dependency_overrides:
    get_session = request.app.dependency_overrides[get_async_session]
    return get_session()
    else:
    get_session = get_async_session
    gen = get_session()
    return await anext(gen)


    Note that get_async_session is a generator:

    async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
    async with async_session_maker() as session:
    yield session


    Now when I run the program I get an exception:


    ERROR:asyncio:Task exception was never retrieved future: <Task finished name='Task-62' coro=<<async_generator_athrow without name>()> exception=IllegalStateChangeError("Method 'close()' can't be called here; method '_connection_for_bind()' is already in progress and this would cause an unexpected state change to <SessionTransactionState.CLOSED: 5>")> Traceback (most recent call last): File "/Users/myrto/PythonProjects/iam/.venv/lib/python3.11/site-packages/mm_db/db.py", line 73, in get_async_session yield session GeneratorExit
    ​

    The program still runs fine despite the exception, but I don't think we should just leave the exception there. What am I doing wrong? Why is this exception thrown?

    Continue reading...

Compartilhe esta Página