Skip to content

Typing: include field type in Attribute type signature #729

Open
@Tinche

Description

@Tinche

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    TypingTyping/stub/Mypy/PyRight related bugs.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions