[flake8-annotations] Correct syntax for typing.Union in suggested return type fixes for ANN20x rules (#16025)

When suggesting a return type as a union in Python <=3.9, we now avoid a
`TypeError` by correctly suggesting syntax like `Union[int,str,None]`
instead of `Union[int | str | None]`.
This commit is contained in:
Dylan 2025-02-07 17:17:20 -06:00 committed by GitHub
parent a29009e4ed
commit 3a806ecaa1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 20 additions and 32 deletions

View file

@ -1437,33 +1437,22 @@ pub fn typing_optional(elt: Expr, binding: Name) -> Expr {
}
/// Format the expressions as a `typing.Union`-style union.
///
/// Note: It is a syntax error to have `Union[]` so the caller
/// should ensure that the `elts` argument is nonempty.
pub fn typing_union(elts: &[Expr], binding: Name) -> Expr {
fn tuple(elts: &[Expr], binding: Name) -> Expr {
match elts {
[] => Expr::Tuple(ast::ExprTuple {
elts: vec![],
ctx: ExprContext::Load,
range: TextRange::default(),
parenthesized: true,
}),
[Expr::Tuple(ast::ExprTuple { elts, .. })] => typing_union(elts, binding),
[elt] => elt.clone(),
[rest @ .., elt] => Expr::BinOp(ast::ExprBinOp {
left: Box::new(tuple(rest, binding)),
op: Operator::BitOr,
right: Box::new(elt.clone()),
range: TextRange::default(),
}),
}
}
Expr::Subscript(ast::ExprSubscript {
value: Box::new(Expr::Name(ast::ExprName {
id: binding.clone(),
id: binding,
range: TextRange::default(),
ctx: ExprContext::Load,
})),
slice: Box::new(tuple(elts, binding)),
slice: Box::new(Expr::Tuple(ast::ExprTuple {
range: TextRange::default(),
elts: elts.to_vec(),
ctx: ExprContext::Load,
parenthesized: false,
})),
ctx: ExprContext::Load,
range: TextRange::default(),
})