MagicStack / MagicStack/asyncpg
Typing: Correctly set types when getting `Record` fields
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 8.1k
- Forks
- 468
- PR merge metrics
- No merged PRs in 30d
Description
Consider the following:
```python
import asyncio
import asyncpg
async def main() -> int:
connection_string = "postgresql://postgres:postgres@127.0.0.1:5432/postgres"
conn = await asyncpg.connect(connection_string)
result = await conn.fetch("SELECT 1 + 1 AS num", record_class=Row)
row = result[0]
num = row["num"]
print(type(num))
return num # mypy error: Returning Any from function declared to return "int"
class Row(asyncpg.Record):
num: int
if __name__ == "__main__":
asyncio.run(main())
```
In essence, the type of `num` is `Any` instead of `int`. I tried to make `Row` inherit from `TypedDict` or use a `dataclass`, both failed.
I'll also be happy to help develop this feature with some general guidance.
Contributor guide
No contributing guide indexed for this repository
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 conn.fetch(..., record_class=Row) example and the asyncpg.Record field access shown in the issue. Investigate how the declared Row.num annotation could affect the inferred type of row["num"]. Done means the example's num is inferred as int and no longer produces mypy's Any return error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- postgresql, python
- Domain
- databases
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100