Skip to content

Fix narrowing from object to Optional #4118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions mypy/meet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions test-data/unit/check-optional.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]
6 changes: 3 additions & 3 deletions test-data/unit/check-unions.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]]'
reveal_type(x) # E: Revealed type is 'Union[builtins.list[Tuple[builtins.str, builtins.str]], builtins.None]'

for y in x: pass
if x:
for y in x: pass
[builtins fixtures/dict.pyi]
[out]

Expand Down