Skip to content

Commit 23b71df

Browse files
ilevkivskyiJukkaL
authored andcommitted
Fix narrowing from object to Optional (#4118)
Previously: ``` x: object y: Optional[int] x = y reveal_type(x) # builtins.int ``` This was unexpected and may be unsafe. Fix this by considering object as overlapping with everything (including None).
1 parent 4a10e05 commit 23b71df

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

mypy/meet.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,10 @@ class C(A, B): ...
8080
# Any overlaps with everything
8181
if isinstance(t, AnyType) or isinstance(s, AnyType):
8282
return True
83+
# object overlaps with everything
84+
if (isinstance(t, Instance) and t.type.fullname() == 'builtins.object' or
85+
isinstance(s, Instance) and s.type.fullname() == 'builtins.object'):
86+
return True
8387

8488
# Since we are effectively working with the erased types, we only
8589
# need to handle occurrences of TypeVarType at the top level.

test-data/unit/check-optional.test

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,3 +642,11 @@ def test_or_shortcut(value: Optional[Any]) -> None:
642642
if not value or value.get('foo') == 'hello':
643643
pass
644644
[builtins fixtures/bool.pyi]
645+
646+
[case testNarrowingFromObjectToOptional]
647+
from typing import Optional
648+
x: object
649+
y: Optional[int]
650+
x = y
651+
reveal_type(x) # E: Revealed type is 'Union[builtins.int, builtins.None]'
652+
[out]

test-data/unit/check-unions.test

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -902,10 +902,10 @@ x: object
902902
a: Any
903903
d: Dict[str, Tuple[List[Tuple[str, str]], str]]
904904
x, _ = d.get(a, (None, None))
905-
# FIXME: fix narrow_declared_type for narrowed Optional types.
906-
reveal_type(x) # E: Revealed type is 'builtins.list[Tuple[builtins.str, builtins.str]]'
905+
reveal_type(x) # E: Revealed type is 'Union[builtins.list[Tuple[builtins.str, builtins.str]], builtins.None]'
907906

908-
for y in x: pass
907+
if x:
908+
for y in x: pass
909909
[builtins fixtures/dict.pyi]
910910
[out]
911911

0 commit comments

Comments
 (0)