-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Incomplete or inconsistent Literal and Union behavior on conditional checks #9220
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
i discovered similar |
Yeah, the behavior seems inconsistent. I'm not sure about the |
I opened PR #9288 that at least fixes the walrus operator usage for the property case. I would be grateful for any kind of feedback :) The |
…g in if statements (#9297) This adds support for union narrowing in if statements when condition value has defined literal annotations in `__bool__` method. Value is narrowed based on the `__bool__` method return annotation and this works even if multiple instances defines the same literal value for `__bool__` method return type. This PR also works well with #9288 and makes below example to work as expected: ```python class A: def __bool__(self) -> Literal[True]: ... class B: def __bool__(self) -> Literal[False]: ... def get_thing() -> Union[A, B]: ... if x := get_thing(): reveal_type(x) # Revealed type is '__main__.A' else: reveal_type(x) # Revealed type is '__main__.B' ``` Partially fixes #9220
Uh oh!
There was an error while loading. Please reload this page.
Used mypy version:
0.782
I stumbled upon some incomplete behavior related to
Literal
andUnion
. In most casesUnion
is not properly expanded upon conditional check when dealing with literals. Below example should describe clearly the situation.I would expect that all examples will give the same result as the one with
is_ok
property. Maybe thebool()
example would require some additional thought but it would seem wise to make it also work. Also, walrus operator makes it so that even theis_ok
property example does not work. Other examples behave the same as before:The text was updated successfully, but these errors were encountered: