`return await ...` not working properly
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Mypy incorrectly raises an error when i return await ...
To Reproduce
I cant seem to reproduce without using SQLAlchemy, but here is an MRE with it. Its possible this issue belongs in SQLAlchemy, however i was more inclined to ask here because the second implementation works correctly
from __future__ import annotations
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class Model(Base):
__tablename__ = "model"
id: Mapped[int] = mapped_column(autoincrement=True, primary_key=True)
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
session = AsyncSession(engine)
async def get_by_id(id: int) -> Model | None:
return await session.scalar(select(Model).where(Model.id == id))
I get the following error for get_by_id:
error: Returning Any from function declared to return "Model | None" [no-any-return]
If i change the implementation to this though:
async def get_by_id(id: int) -> Model | None:
result = await session.scalar(select(Model).where(Model.id == id))
return result
The error dissapears
Expected Behavior
Mypy should not show an error for the first implementation
Actual Behavior
It does
Your Environment
- Mypy version used: 1.15.0
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files):
[tool.mypy]
python_version = "3.13"
disallow_untyped_defs = true
disallow_any_unimported = true
no_implicit_optional = true
check_untyped_defs = true
warn_return_any = true
warn_unused_ignores = true
show_error_codes = true
- Python version used: 3.13.2
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the supplied Python reproducer using SQLAlchemy's AsyncSession.scalar and compare the inline await with the local-variable form under mypy 1.15.0 and the shown warn_return_any configuration. Trace how mypy handles the awaited expression and verify the fix with a regression test showing that both forms avoid the no-any-return error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python, sqlalchemy, sqlite
- Domain
- databases, devtools, tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100