Skip to content

Commit 848f821

Browse files
ddfishergvanrossum
authored andcommitted
Get type information from isinstance assertions (#1346)
* Get type information from isinstance assertions Fixes #475. * Add test
1 parent aa319ea commit 848f821

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

mypy/checker.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1709,6 +1709,16 @@ def visit_operator_assignment_stmt(self,
17091709
def visit_assert_stmt(self, s: AssertStmt) -> Type:
17101710
self.accept(s.expr)
17111711

1712+
# If this is asserting some isinstance check, bind that type in the following code
1713+
true_map, _ = find_isinstance_check(
1714+
s.expr, self.type_map,
1715+
self.typing_mode_weak()
1716+
)
1717+
1718+
if true_map:
1719+
for var, type in true_map.items():
1720+
self.binder.push(var, type)
1721+
17121722
def visit_raise_stmt(self, s: RaiseStmt) -> Type:
17131723
"""Type check a raise statement."""
17141724
self.breaking_out = True

mypy/test/data/check-isinstance.test

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -817,3 +817,10 @@ def f(x: Union[A, B]) -> None:
817817
if not isinstance(x, B):
818818
f(x)
819819
[builtins fixtures/isinstance.py]
820+
821+
[case testAssertIsinstance]
822+
def f(x: object):
823+
assert isinstance(x, int)
824+
y = 0 # type: int
825+
y = x
826+
[builtins fixtures/isinstance.py]

0 commit comments

Comments
 (0)