Skip to content

Conversation

kprzybyla
Copy link
Contributor

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:

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()  # Revealed type is '__main__.A'
else:
    reveal_type()  # Revealed type is '__main__.B'

Partially fixes #9220

Copy link
Collaborator

@JukkaL JukkaL left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! The code is nice and clean, and there is good test coverage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Incomplete or inconsistent Literal and Union behavior on conditional checks
2 participants