-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Local type inference of numeric variables #8747
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
Comments
When you say The workaround is to do something like:
|
I understand the workaround -- I guess my question is, can the inference algorithm be extended to infer type float for foo in the example above, in a similar way to how 0.770 extended it to infer List[int] for foo in:
|
You can use
Note the print is necessary, as mentioned in #6963 / #6959 (comment) |
More generally, it may make sense to generalize type inference to allow cases like this (this isn't supported by
The implementation could use the same approach used for the list example shown above (partial types). Before moving forward with this, however, we'd need some evidence of how often this would be helpful. It's possible that generalizing partial types to floats wouldn't help much. It might better to improve the error messages to propose adding a |
From my own POV, I think smarter inference would always be preferable to having to add an annotation. However, I can imagine at least in principle a kind of code where this would not be helpful: if someone was relying on the type checker to help them keeps (And if there are enough of those kind of uses to make a change to the inference undesirable, then a better still error message would be a good improvement.) |
Another thing that might make better inference undesirable if the better inference only works in, say, 30% of typical use cases. It may be better to have something where you consistently have to add an annotation compared to something where you usually need to add an annotation but sometimes not. Predictability is nice. |
I have a very simple example program that produces surprising and (I think...) wrong behavior:
Running mypy against this file yields
But
foo
could(/should) be inferred as a float in this environment. I draw this conclusion from PEP-484(although this is not about function arguments per se).
I know that some improvements have been recently been made to type inference in 0.770 to use information from second (or subsequent) assignments, rather than just the first assignment. So maybe a widening from int to float could be implemented in the same way...?
The text was updated successfully, but these errors were encountered: