NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Middle82 views

async def get_user(user_id: int, db: AsyncSession): try: user = await db.get(User, user_id) return user finally: await db.close() return None q = get_user(76576, )

Practice

AI answer

There are several problems in the example:

  • The call get_user(76576, ) does not pass the required db argument, so it will immediately raise a TypeError. Also, the result of async def must be obtained using await.
  • return None inside finally will always replace the result from try and suppress any exception that may have occurred.
  • If the session was passed in by the calling code, you generally should not close it inside the function: the session's lifecycle should be managed by its owner.

For example:

async def get_user(user_id: int, db: AsyncSession) -> User | None:
    return await db.get(User, user_id)

async with async_session() as db:
    user = await get_user(76576, db)

If the function creates the session itself, use its asynchronous context manager (async with) and do not add a return in `finally.