Infer descriptor type
- Dominant language
- Rust
- Stars
- 7k
- Forks
- 516
- PR merge metrics
- No merged PRs in 30d
Description
This is a copy of this enhancement I proposed for mypy: https://github.com/python/mypy/issues/10246
I use this inference in a project through a mypy plugin, I'm trying out pyrefly so I'm curious if this is something you'd consider allowing or not (feel free to close the issue in that case).
## 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.
## Other
This is kind of how dataclasses are typed (although dataclasses have more magic involved).
Possibly this could be opt-in through some mechanism like a metaclass or a class decorator, to make it more explicit.
[sandbox example](https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0AqADrow1eplQNUAYyio4ceJ269%2Bk6XIVwANHUgwomESID6AFQCaABQCidALx1zzGADVUlABRCQFm7a%2BAJQm6CJainQAwrjocNLoDF4A4jDoMJQQMgDa-nYAukGIInSldJgwYHSmpqwQDDVeSlBgejKx8RgMiNVWdkUlZUPNYITtcQn8TuOdiaFDAAK4AG4ZULioxuhDFVU1bDANpk2GrXS42ABWPQBysTB6F5dMxDBBdAC0AHx0AOQxEy6v2K2yGZUIEPmZSWq0o602g1Ku2qpgORxOLUeVyxz1cDju6Xe316ARBYPBkLCoKRlRRaMaIxxOJeMHx9yJPzy9gAPn8AbMGMDEWCIFUnpw4HQCTAyeSwZRDgBXSjbEbCoYKhjK1WnMYdSahcLySK2fCobiwDxQCCYWWlfA9fmTbKsBj5RzRfVdLwARgADCEqUbtHRTebiLAAOoQOAACztdAdnESHqd3v9gdCCw0smNcGDJrNFpgABEpLntAmk66PQYjF5M1SFatUFBTCyvGHi1abYR8O86ABiAAFabm6GbMFb7dcnaLEfcrZtDb7A8HyYYIkn047XYX0bjq9K69degA7rhFUY6NaANYwT2AxIuxL5LcwFtt3fzqMx2Mr-tjw3d9PxnV453DWAy00PNfSCVcQKnL9Zz3KDywiOAjyHOgAEEGAYTJsEVBgYFsShqEoEQQB0EBiOgTCyAodcAFUGGgepSH0RV0BkNiOlCZEwF4GgpFMdBFRobAMi8atEg5Oh4koBNNW1fRfBuCSpKUuhgHwABfXwqJosgFTAKBSEIBhaCgJi6GsUhTPMhSMBwAg6HGSA2GVKQIFiQgRHXABlGAH1jfDiDgRAAHoopMypzMIXg2CitIoswXAZDgKKPIgLzKB82Iov0Xg6FQZZUGgVBsFgdzYk87y%2BO2XBiEazCRDIBhY1iD5YTgXzticXwAGZCB9AAmQz0BAPSaNkNjVgAMWgGAKDQLA8CIRi9KAA)
Contributor guide
Assessment
This issue has not been assessed yet.