Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Infer descriptor type #10246

Open
iwanb opened this issue Mar 25, 2021 · 1 comment
Open

Infer descriptor type #10246

iwanb opened this issue Mar 25, 2021 · 1 comment
Labels
feature topic-descriptors Properties, class vs. instance attributes

Comments

@iwanb
Copy link

iwanb commented Mar 25, 2021

Feature

For the common case of a descriptor which behaves like a normal attribute, infer:

class X:
    y: int = descriptor()

to:

class X:
    y: descriptor[int] = descriptor()

if descriptor is a Generic with one parameter. Extra checks should also be done to make sure that the descriptor is properly typed to behave like an attribute of that type (__get__ and __set__ expect that type on an instance).

Pitch

Type annotations apply to object instances by default, so it's strange to see y: descriptor[int] as type annotation while x.y returns an int.
You could also see a normal attribute as an invisible descriptor whose behavior is to set __dict__[name] (and raise AttributeError on the class), so this could be a way to unify these things.

It's also related to:
#7724
#5481

I implemented it partially as a plugin but only for my custom descriptors.

@iwanb iwanb added the feature label Mar 25, 2021
@anis-campos
Copy link

anis-campos commented Nov 26, 2021

Is there any way to do this without a plugin ? I'm so frustrated, seeing what descriptor is able to do, it's so disappointing to not be able to properly type the attribute.

Also my implementation of a descriptor is used as a convenient factory that gets the concrete type from the __annotations__ of the owner object.

    def __set_name__(self, owner: Any, name: str) -> None:
        self.public_name = name
        self.private_name = "_" + name
        self.type_ = owner.__annotations__[self.public_name]

So it would be nice to also have a way to just ignore the type of __get__ in that case, the annotation is just the only typing necessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature topic-descriptors Properties, class vs. instance attributes
Projects
None yet
Development

No branches or pull requests

3 participants