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

Incompatible types: Union[bool, A] and Optional[A] #11043

Closed
carmocca opened this issue Sep 2, 2021 · 2 comments · Fixed by #10389
Closed

Incompatible types: Union[bool, A] and Optional[A] #11043

carmocca opened this issue Sep 2, 2021 · 2 comments · Fixed by #10389
Labels
bug mypy got something wrong

Comments

@carmocca
Copy link

carmocca commented Sep 2, 2021

Bug Report

from typing import Union, Optional


class Foo:
    ...
    
    
class Bar(Foo):
    ...
    
    
class Thing:
    thing: Optional[Foo]
    
    def errors(self, x: Union[bool, Foo]) -> None:
        if x is True:
            self.thing = Bar()
        elif x is False:
            self.thing = None
        else:
            self.thing = x
            
    def works(self, x: Union[bool, Foo]) -> None:
        if isinstance(x, bool):
            self.thing = Bar() if x else None
        else:
            self.thing = x

I would expect that errors and works are equal, but errors produces an error.

Sorry if this is a duplicate, I tried googling it!

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.10&gist=f17cd6e5962f2edd358143dcce83ab51

Expected Behavior

No error

Actual Behavior

main.py:21: error: Incompatible types in assignment (expression has type "Union[bool, Foo]", variable has type "Optional[Foo]")
Found 1 error in 1 file (checked 1 source file)

Your Environment

See link above - can be reproduced in all versions

@carmocca carmocca added the bug mypy got something wrong label Sep 2, 2021
@erictraut
Copy link

Mypy doesn't currently narrow bool types when the value is compared against True or False, so the type of x within the else clause is Union[bool, Foo]. This new capability would need to be added to make the above code type check without error.

For now, you could work around it using the technique you identified, or you can add a assert not isinstance(x, bool) statement in the else clause of the errors method.

@hauntsaninja
Copy link
Collaborator

Thanks, this will be fixed by #10389

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

Successfully merging a pull request may close this issue.

3 participants