Skip to content

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

Closed

Description

@carmocca

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

Activity

  1. erictraut commented on Sep 2, 2021

    @erictraut

    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.

  2. hauntsaninja commented on Oct 31, 2021

    @hauntsaninja
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions