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.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
postgresql, python
Domain
databases

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.

Description

Consider the following:

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.

Dominant language
Python
Stars
8.1k
Forks
469
Avg merge
2d 20h
Merged PRs (30d)
9

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.

More from MagicStack/asyncpg

All issues in MagicStack/asyncpg

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.