-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Type inference on owner
argument to __set_name__
#7039
Comments
Pyright is working as designed here. A type checker cannot make the assumptions that you seem to think it should in this case. As you point out, you can remove the ambiguity by providing an explicit specialization for |
In case it wasn't clear: this was a feature request, not a bug report. Could you please explain your statement:
For descriptors defined in a class, the class context is known statically, and that's the same class that is passed as PS: Having to provide explicit specialisation is brittle, because it has to be done via a forward reference. It is also unsightly and unnecessarily laborious, but perhaps that's a matter of taste. |
The specialized type of an object is established at the time it is constructed. The The error that you're seeing is because there's insufficient information for a type checker to infer the type of the lambda that you're passing to the constructor. |
I'm aware of all of that, thank you (although I might disagree with your first sentence, depending on the specific meaning of "time it is constructed"). Here, the class context in which the descriptor object is constructed is known statically, as is the way in which The fact that a specific type-checker might not have access to that information is a design choice/limitation of the type-checker, hence the feature request... |
Because of the circumstances under which
__set_name__
is invoked, it should be possible to perform type inference on itsowner
argument, in a way which could be used to statically typecheck other components of a descriptor.As a brief motivating example, below is a sketch of descriptor for a validated mutable attribute of integer type:
In Pylance with strict typechecking rules, the definition of the
x
descriptor raises the following errors:Explicitly providing a hint for the
InstanceT
type removes the errors:Performing inference on the
owner
argument toIntAttr.__set_name__
in the context ofclass C
would ideally result inC
being inferred as a value forInstanceT
, allowing for static typecheking of thevalidator
lambda function without the need for an explicit type hint.Related issues for Mypy:
Sister issue for Mypy: python/mypy#16796
The text was updated successfully, but these errors were encountered: