Don't skip visiting non-tuple slice in typing.Annotated subscripts (#17201)

Fixes: #17196

## Summary

Skipping these nodes for malformed type expressions would lead to
incorrect semantic state, which can in turn mean we emit false positives
for rules like `unused-variable`(`F841`)

## Test Plan

`cargo nextest run`
This commit is contained in:
David Salvisberg 2025-04-04 15:17:40 +02:00 committed by GitHub
parent 5cee346744
commit 33a56f198b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 27 additions and 1 deletions

View file

@ -1669,7 +1669,15 @@ impl<'a> Visitor<'a> for Checker<'a> {
}
self.visit_expr_context(ctx);
} else {
debug!("Found non-Expr::Tuple argument to PEP 593 Annotation.");
if self.semantic.in_type_definition() {
// this should potentially trigger some kind of violation in the
// future, since it would indicate an invalid type expression
debug!("Found non-Expr::Tuple argument to PEP 593 Annotation.");
}
// even if the expression is invalid as a type expression, we should
// still visit it so we don't accidentally treat variables as unused
self.visit_expr(slice);
self.visit_expr_context(ctx);
}
}
Some(typing::SubscriptKind::TypedDict) => {

View file

@ -4263,4 +4263,22 @@ lambda: fu
&[],
);
}
#[test]
fn gh_issue_17196_regression_test() {
flakes(
r#"
from typing import Annotated
def type_annotations_from_tuple():
annos = (str, "foo", "bar")
return Annotated[annos]
def type_annotations_from_filtered_tuple():
annos = (str, None, "foo", None, "bar")
return Annotated[tuple([a for a in annos if a is not None])]
"#,
&[],
);
}
}