Skip to content

Commit ed67bfc

Browse files
ddfishergvanrossum
authored andcommitted
Handle UnionType correctly in true_or_false (#3510)
Fixes #3508.
1 parent 72168fa commit ed67bfc

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

mypy/types.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1699,6 +1699,10 @@ def true_or_false(t: Type) -> Type:
16991699
"""
17001700
Unrestricted version of t with both True-ish and False-ish values
17011701
"""
1702+
if isinstance(t, UnionType):
1703+
new_items = [true_or_false(item) for item in t.items]
1704+
return UnionType.make_simplified_union(new_items, line=t.line, column=t.column)
1705+
17021706
new_t = copy_type(t)
17031707
new_t.can_be_true = type(new_t).can_be_true
17041708
new_t.can_be_false = type(new_t).can_be_false

test-data/unit/check-optional.test

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,3 +594,12 @@ x: Optional[Union[int, str]]
594594
reveal_type(x) # E: Revealed type is 'Union[builtins.int, builtins.str, builtins.None]'
595595
y: Optional[Union[int, None]]
596596
reveal_type(y) # E: Revealed type is 'Union[builtins.int, builtins.None]'
597+
598+
[case testUnionTruthinessTracking]
599+
from typing import Optional, Any
600+
def test_or_shortcut(value: Optional[Any]) -> None:
601+
if not value:
602+
pass
603+
if not value or value.get('foo') == 'hello':
604+
pass
605+
[builtins fixtures/bool.pyi]

0 commit comments

Comments
 (0)