[red-knot] Fix: Infer type for typing.Union[..] tuple expression (#14510)

## Summary

Fixes a panic related to sub-expressions of `typing.Union` where we fail
to store a type for the `int, str` tuple-expression in code like this:
```
x: Union[int, str] = 1
```

relates to [my
comment](https://github.com/astral-sh/ruff/pull/14499#discussion_r1851794467)
on #14499.

## Test Plan

New corpus test
This commit is contained in:
David Peter 2024-11-21 11:49:20 +01:00 committed by GitHub
parent 47f39ed1a0
commit f684b6fff4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 11 additions and 4 deletions

View file

@ -4568,10 +4568,14 @@ impl<'db> TypeInferenceBuilder<'db> {
UnionType::from_elements(self.db, [param_type, Type::none(self.db)]) UnionType::from_elements(self.db, [param_type, Type::none(self.db)])
} }
KnownInstanceType::Union => match parameters { KnownInstanceType::Union => match parameters {
ast::Expr::Tuple(t) => UnionType::from_elements( ast::Expr::Tuple(t) => {
let union_ty = UnionType::from_elements(
self.db, self.db,
t.iter().map(|elt| self.infer_type_expression(elt)), t.iter().map(|elt| self.infer_type_expression(elt)),
), );
self.store_expression_type(parameters, union_ty);
union_ty
}
_ => self.infer_type_expression(parameters), _ => self.infer_type_expression(parameters),
}, },
KnownInstanceType::TypeVar(_) => todo_type!(), KnownInstanceType::TypeVar(_) => todo_type!(),

View file

@ -0,0 +1,3 @@
from typing import Union
x: Union[int, str] = 1