Skip to content

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

Description

@carmocca

Bug Report

fromtypingimportUnion, OptionalclassFoo:
...
classBar(Foo):
...
classThing:
thing: Optional[Foo]
deferrors(self, x: Union[bool, Foo]) ->None:
ifxisTrue:
self.thing=Bar()
elifxisFalse:
self.thing=Noneelse:
self.thing=xdefworks(self, x: Union[bool, Foo]) ->None:
ifisinstance(x, bool):
self.thing=Bar() ifxelseNoneelse:
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: Incompatibletypesinassignment (expressionhas type "Union[bool, Foo]", variablehas type "Optional[Foo]")
Found1errorin1file (checked1sourcefile)

Your Environment

See link above - can be reproduced in all versions

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