Skip to content

Commit 0d9e724

Browse files
committed
Assertions prune the type-inference tree.
This means that you can write x = somethingReturningObject assert isinstance(x, T) and the compiler will infer that 'x' has 'T' if you pass the assertion.
1 parent cd609e4 commit 0d9e724

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

typed_python/compiler/function_conversion_context.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2116,6 +2116,10 @@ def _convert_statement_ast(self, ast, variableStates: FunctionStackState, contro
21162116
if msgExpr is not None:
21172117
expr_context.pushException(AssertionError, msgExpr)
21182118

2119+
if not definitelyFails:
2120+
# we are implicitly the 'True' case of this condition
2121+
self.restrictByCondition(variableStates, ast.test, result=True)
2122+
21192123
return expr_context.finalize(None, exceptionsTakeFrom=ast), not definitelyFails
21202124

21212125
if ast.matches.FunctionDef:

typed_python/compiler/tests/type_inference_test.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,3 +410,24 @@ def f(x: OneOf(None, str)):
410410
return localVariableTypesKnownToCompiler()
411411

412412
assert f("hi")['x'] == str
413+
414+
def test_assertion_prunes_types(self):
415+
@Entrypoint
416+
def f(x: OneOf(None, str)):
417+
assert x is not None
418+
419+
return x
420+
421+
assert f.resultTypeFor(str).typeRepresentation is str
422+
assert f.resultTypeFor(type(None)).typeRepresentation is str
423+
424+
def test_branch_with_raise_prunes_types(self):
425+
@Entrypoint
426+
def f(x: OneOf(None, str)):
427+
if x is None:
428+
raise Exception("FAIL")
429+
430+
return x
431+
432+
assert f.resultTypeFor(str).typeRepresentation is str
433+
assert f.resultTypeFor(type(None)).typeRepresentation is str

0 commit comments

Comments
 (0)