Skip to content

Commit d83aece

Browse files
ddfishergvanrossum
authored andcommitted
Make join(None, T) produce Optional[T] in strict-optional (#1999)
Fixes #1820.
1 parent 0cec417 commit d83aece

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

mypy/join.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,9 @@ def join_types(s: Type, t: Type) -> Type:
6666
if isinstance(s, ErasedType):
6767
return t
6868

69+
if isinstance(s, UnionType) and not isinstance(t, UnionType):
70+
s, t = t, s
71+
6972
if isinstance(s, NoneTyp) and not isinstance(t, NoneTyp):
7073
s, t = t, s
7174

@@ -114,8 +117,12 @@ def visit_none_type(self, t: NoneTyp) -> Type:
114117
if experiments.STRICT_OPTIONAL:
115118
if isinstance(self.s, (NoneTyp, UninhabitedType)):
116119
return t
120+
elif isinstance(self.s, UnboundType):
121+
return AnyType()
122+
elif isinstance(self.s, Void) or isinstance(self.s, ErrorType):
123+
return ErrorType()
117124
else:
118-
return self.default(self.s)
125+
return UnionType.make_simplified_union([self.s, t])
119126
else:
120127
if not isinstance(self.s, Void):
121128
return self.s

test-data/unit/check-optional.test

+8
Original file line numberDiff line numberDiff line change
@@ -330,3 +330,11 @@ def lookup_field(name, obj):
330330
[out]
331331
main: note: In function "lookup_field":
332332
main:10: error: Need type annotation for variable
333+
334+
[case testTernaryWithNone]
335+
reveal_type(None if bool() else 0) # E: Revealed type is 'Union[builtins.int, builtins.None]'
336+
[builtins fixtures/bool.py]
337+
338+
[case testListWithNone]
339+
reveal_type([0, None, 0]) # E: Revealed type is 'builtins.list[Union[builtins.int, builtins.None]]'
340+
[builtins fixtures/list.py]

0 commit comments

Comments
 (0)