Skip to content
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

Add support for using __bool__ method literal value in union narrowing in if statements #9297

Merged
merged 2 commits into from
Aug 14, 2020
Merged

Add support for using __bool__ method literal value in union narrowing in if statements #9297

merged 2 commits into from
Aug 14, 2020

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