MagicStack / MagicStack/asyncpg

Typing: Correctly set types when getting `Record` fields

Open
#1,210 0 comments 0 reactions 0 assignees View on GitHub

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

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.