Typing: include field type in Attribute type signature

Open
#729 13 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
38/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
python

Research direction

Start with the attr.Attribute type and the reveal_type example in the issue, then inspect how attrs exposes field types to static checkers. Done means attr.fields(A).a is inferred as attr.Attribute[int] and the load_projection example type-checks with the field's value type.

Written by the indexing model from the issue text.

Description

Typing

I'm already using attrs to implement several internal ORMs, and attrs (with cattrs) is very good for this. However I find myself missing a feature.

Consider the following code:

import attr


@attr.define
class A:
    a: int


reveal_type(attr.fields(A).a)

The revealed type is attr.Attribute[Any]. What would it take for mypy to think the type was attr.Attribute[int]?

This would be hugely useful for enabling type-safe projections. Often times, whether you're using a relational database or a key-value store like Mongo, you're only interested in a subset of the data. It's natural to represent your database model as a fully type-annotated attrs class, and it would be great to be able to implement something like:

from bson import ObjectId  # Pretend we're working with Mongo

async def load_projection(id: ObjectId, field: attr.Attribute[T]) -> T:
    pass

my_a = await load_projection(id, fields(A).a)

And have mypy properly check it.

Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Contributor guide

Open the contributing guide

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 python-attrs/attrs

All issues in python-attrs/attrs

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.