From fadfcfff6478d7a589fe4ed820379070cfc501cb Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Fri, 13 Oct 2017 17:08:42 +0200 Subject: [PATCH 1/2] Fix narrowing from object to Optional --- mypy/meet.py | 4 ++++ test-data/unit/check-optional.test | 8 ++++++++ test-data/unit/check-unions.test | 4 ++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/mypy/meet.py b/mypy/meet.py index 3e883b53fd4d..53b9f524b1ca 100644 --- a/mypy/meet.py +++ b/mypy/meet.py @@ -80,6 +80,10 @@ class C(A, B): ... # Any overlaps with everything if isinstance(t, AnyType) or isinstance(s, AnyType): return True + # object overlaps with everything + if (isinstance(t, Instance) and t.type.fullname() == 'builtins.object' or + isinstance(s, Instance) and s.type.fullname() == 'builtins.object'): + return True # Since we are effectively working with the erased types, we only # need to handle occurrences of TypeVarType at the top level. diff --git a/test-data/unit/check-optional.test b/test-data/unit/check-optional.test index 138643269e89..e44266b30a64 100644 --- a/test-data/unit/check-optional.test +++ b/test-data/unit/check-optional.test @@ -642,3 +642,11 @@ def test_or_shortcut(value: Optional[Any]) -> None: if not value or value.get('foo') == 'hello': pass [builtins fixtures/bool.pyi] + +[case testNarrowingFromObjectToOptional] +from typing import Optional +x: object +y: Optional[int] +x = y +reveal_type(x) # E: Revealed type is 'Union[builtins.int, builtins.None]' +[out] diff --git a/test-data/unit/check-unions.test b/test-data/unit/check-unions.test index 465b1802db85..fe21f7efa60b 100644 --- a/test-data/unit/check-unions.test +++ b/test-data/unit/check-unions.test @@ -902,10 +902,10 @@ x: object a: Any d: Dict[str, Tuple[List[Tuple[str, str]], str]] x, _ = d.get(a, (None, None)) -# FIXME: fix narrow_declared_type for narrowed Optional types. reveal_type(x) # E: Revealed type is 'builtins.list[Tuple[builtins.str, builtins.str]]' -for y in x: pass +if x: + for y in x: pass [builtins fixtures/dict.pyi] [out] From f06e8a5b1c783bd93cf658f866f423e4b9dc2d89 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Fri, 13 Oct 2017 17:43:06 +0200 Subject: [PATCH 2/2] Fix test --- test-data/unit/check-unions.test | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-data/unit/check-unions.test b/test-data/unit/check-unions.test index fe21f7efa60b..0f40b3679a44 100644 --- a/test-data/unit/check-unions.test +++ b/test-data/unit/check-unions.test @@ -902,7 +902,7 @@ x: object a: Any d: Dict[str, Tuple[List[Tuple[str, str]], str]] x, _ = d.get(a, (None, None)) -reveal_type(x) # E: Revealed type is 'builtins.list[Tuple[builtins.str, builtins.str]]' +reveal_type(x) # E: Revealed type is 'Union[builtins.list[Tuple[builtins.str, builtins.str]], builtins.None]' if x: for y in x: pass