-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Union should be automatically inferred when assignment occurs in multiple branches #2611
Comments
Mypy doesn't infer a union here by design. I think the main reasons are
This is closer to a bug in mypy. It sounds like the same issue as #2008. |
That's not necessarily true. I'm suggesting that mypy automatically infer a union only when two branches of a conditional use different types (treating the except and else blocks of a try statement as conditional blocks). So, this would be legal:
but this would not be:
or even this:
|
Closing in favor of #6233, which has more discussion. |
Not sure if this has already been discussed; I couldn't find an exact duplicate although #1094 and #1174 are similar. I have code like this:
but mypy gives an error the assignment in the except block and doesn't infer the union. I tried adding an explicit
# type: Optional[int]
to the first assignment, but then mypy no longer recognizes that x is a non-Optional int in the else block. I ran into this with a try block but I assume an if block would get the same result.Not sure how easy this is to change or if it affects some other behavior in mypy. I have implemented similar logic in the past by inferring types separately from assignments in the two branches and then unifying the two.
The text was updated successfully, but these errors were encountered: