From 17acef12bcf155cd55559174345801d919ac3e10 Mon Sep 17 00:00:00 2001 From: David Fisher Date: Mon, 8 Aug 2016 14:59:47 -0700 Subject: [PATCH 1/2] Make join(None, T) produce Optional[T] --- mypy/join.py | 10 +++++++++- test-data/unit/check-optional.test | 8 ++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/mypy/join.py b/mypy/join.py index d63388d35450..8dd97d20b0ae 100644 --- a/mypy/join.py +++ b/mypy/join.py @@ -66,6 +66,9 @@ def join_types(s: Type, t: Type) -> Type: if isinstance(s, ErasedType): return t + if isinstance(s, UnionType) and not isinstance(t, UnionType): + s, t = t, s + if isinstance(s, NoneTyp) and not isinstance(t, NoneTyp): s, t = t, s @@ -73,6 +76,7 @@ def join_types(s: Type, t: Type) -> Type: return t.accept(TypeJoinVisitor(s)) + class TypeJoinVisitor(TypeVisitor[Type]): """Implementation of the least upper bound algorithm. @@ -114,8 +118,12 @@ def visit_none_type(self, t: NoneTyp) -> Type: if experiments.STRICT_OPTIONAL: if isinstance(self.s, (NoneTyp, UninhabitedType)): return t + elif isinstance(self.s, UnboundType): + return AnyType() + elif isinstance(self.s, Void) or isinstance(self.s, ErrorType): + return ErrorType() else: - return self.default(self.s) + return UnionType.make_simplified_union([self.s, t]) else: if not isinstance(self.s, Void): return self.s diff --git a/test-data/unit/check-optional.test b/test-data/unit/check-optional.test index 2d643fea4648..7c6b3b3a4fae 100644 --- a/test-data/unit/check-optional.test +++ b/test-data/unit/check-optional.test @@ -330,3 +330,11 @@ def lookup_field(name, obj): [out] main: note: In function "lookup_field": main:10: error: Need type annotation for variable + +[case testTernaryWithNone] +reveal_type(None if bool() else 0) # E: Revealed type is 'Union[builtins.int, builtins.None]' +[builtins fixtures/bool.py] + +[case testListWithNone] +reveal_type([0, None, 0]) # E: Revealed type is 'builtins.list[Union[builtins.int, builtins.None]]' +[builtins fixtures/list.py] From 93b57cfe71bc70598dcd668a842214c4b2d00763 Mon Sep 17 00:00:00 2001 From: David Fisher Date: Mon, 8 Aug 2016 16:00:45 -0700 Subject: [PATCH 2/2] remove extraneous blank line --- mypy/join.py | 1 - 1 file changed, 1 deletion(-) diff --git a/mypy/join.py b/mypy/join.py index 8dd97d20b0ae..d6ca21448e41 100644 --- a/mypy/join.py +++ b/mypy/join.py @@ -76,7 +76,6 @@ def join_types(s: Type, t: Type) -> Type: return t.accept(TypeJoinVisitor(s)) - class TypeJoinVisitor(TypeVisitor[Type]): """Implementation of the least upper bound algorithm.