You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Incorrect union narrowing in chained conditionals #12208
class Animal:
name: Literal["animal"]
n_legs: int
class Plant:
name: Literal["plant"]
def get_n_legs(item: Union[Animal, Plant]):
if item.name == "animal" and item.n_legs > 6: # This fails mypy with union-attr for n_legs in Plant
return "Many"
Expected Behavior
Mypy should be able to narrow down chained conditionals as presented. It seems that pylance has no problems with it, for example.
I believe I ran into another occurrence of this. It looks like the type has not been narrowed by the first if statement.
Happens with latest mypy on Python3.8.
Trying it on https://mypy-play.net looks to happen on more recent versions of Python as well.
Activity
erictraut commentedon Feb 19, 2022
Which version of mypy are you using? I'm not able to repro this error with the latest published version.
JelleZijlstra commentedon Mar 19, 2022
Doesn't repro for me either: https://mypy-play.net/?mypy=latest&python=3.10&gist=e2c735beb847d6da4d53477050f3a119
JaviFuentes94 commentedon Mar 22, 2022
Hello again, sorry I made a mistake while testing my minimal example. The problem comes with a Literal that is an enum field:
Here you can reproduce it: https://mypy-play.net/?mypy=latest&python=3.10&gist=dfcdd1d12e53c80d0e58ba5ed8750ccf
mikaelarguedas commentedon Mar 4, 2023
Hey there,
I believe I ran into another occurrence of this. It looks like the type has not been narrowed by the first if statement.
Happens with latest mypy on Python3.8.
Trying it on https://mypy-play.net looks to happen on more recent versions of Python as well.
Reproducible example: https://mypy-play.net/?mypy=latest&python=3.11&flags=verbose&gist=07d004a22a748059c834ff42d690c2ed
erictraut commentedon Aug 13, 2023
The original bug in this issue appears to have been fixed in mypy 1.4.
@mikaelarguedas, your issue is unrelated to OP's bug. The behavior in your sample is expected behavior in mypy.
hauntsaninja commentedon Aug 13, 2023
I fixed this in #11521