Compare commits

...

1 Commits

Author SHA1 Message Date
David Peter
ca0f9dc5d7 [red-knot] Type narrowing for is None 2024-10-14 16:09:07 +02:00
2 changed files with 32 additions and 7 deletions

View File

@@ -0,0 +1,16 @@
# Type Narrowing
## `… is None`
```py
x = None if flag else 1
reveal_type(x) # revealed: None | Literal[1]
if x is None:
# TODO: this should be None
reveal_type(x) # revealed: None | Literal[1] & None
else:
# TODO: this should be Literal[1]
reveal_type(x) # revealed: None | Literal[1]
```

View File

@@ -155,13 +155,22 @@ impl<'db> NarrowingConstraintsBuilder<'db> {
let inference = infer_expression_types(self.db, expression);
for (op, comparator) in std::iter::zip(&**ops, &**comparators) {
let comp_ty = inference.expression_ty(comparator.scoped_ast_id(self.db, scope));
if matches!(op, ast::CmpOp::IsNot) {
let ty = IntersectionBuilder::new(self.db)
.add_negative(comp_ty)
.build();
self.constraints.insert(symbol, ty);
};
// TODO other comparison types
match op {
ast::CmpOp::IsNot => {
let ty = IntersectionBuilder::new(self.db)
.add_negative(comp_ty)
.build();
self.constraints.insert(symbol, ty);
}
ast::CmpOp::Is => {
let ty = IntersectionBuilder::new(self.db)
.add_positive(comp_ty)
.build();
self.constraints.insert(symbol, ty);
}
_ => {} // TODO other comparison types
}
}
}
}