python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.56k stars 2.84k forks source link

Mypy doesn't recognize that truth value testing for sequences like `and my_list` result in a boolean type #18181

Closed Yazan-Sharaya closed 2 days ago

Yazan-Sharaya commented 2 days ago

Bug Report

Mypy fails to recognize that truth value testing results in boolean for sequences.

To Reproduce

my_list = [1]
should_update: bool = True and my_list

Actual Behavior

Mypy thinks the type of the new variable is whatever the type of the sequence is, list[int] in this case. error: Incompatible types in assignment (expression has type "list[int]", variable has type "bool") [assignment]

Your Environment

JelleZijlstra commented 2 days ago

Mypy is correct here. The and operator evaluates to its right-hand side if the left-hand side is truthy. You can try it in the REPL:

>>> my_list = [1]
... should_update: bool = True and my_list
... 
>>> should_update
[1]
Yazan-Sharaya commented 1 day ago

You are right, I don't know how I didn't catch that. Thanks for the quick response!