Treat `typing.Annotated` subscripts as type definitions (#10285)

## Summary

I think this code has existed since the start of `typing.Annotated`
support (https://github.com/astral-sh/ruff/pull/333), and was then
overlooked over a series of refactors.

Closes https://github.com/astral-sh/ruff/issues/10279.
This commit is contained in:
Charlie Marsh 2024-03-07 16:51:54 -08:00 committed by GitHub
parent 7a675cd822
commit 57be3fce90
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 29 additions and 1 deletions

View File

@ -0,0 +1,7 @@
"""Test: ensure that we treat strings in `typing.Annotation` as type definitions."""
from pathlib import Path
from re import RegexFlag
from typing import Annotated
p: Annotated["Path", int] = 1

View File

@ -1348,7 +1348,7 @@ impl<'a> Visitor<'a> for Checker<'a> {
{
let mut iter = elts.iter();
if let Some(expr) = iter.next() {
self.visit_expr(expr);
self.visit_type_definition(expr);
}
for expr in iter {
self.visit_non_type_definition(expr);

View File

@ -55,6 +55,7 @@ mod tests {
#[test_case(Rule::UnusedImport, Path::new("F401_20.py"))]
#[test_case(Rule::UnusedImport, Path::new("F401_21.py"))]
#[test_case(Rule::UnusedImport, Path::new("F401_22.py"))]
#[test_case(Rule::UnusedImport, Path::new("F401_23.py"))]
#[test_case(Rule::ImportShadowedByLoopVar, Path::new("F402.py"))]
#[test_case(Rule::ImportShadowedByLoopVar, Path::new("F402.ipynb"))]
#[test_case(Rule::UndefinedLocalWithImportStar, Path::new("F403.py"))]

View File

@ -0,0 +1,20 @@
---
source: crates/ruff_linter/src/rules/pyflakes/mod.rs
---
F401_23.py:4:16: F401 [*] `re.RegexFlag` imported but unused
|
3 | from pathlib import Path
4 | from re import RegexFlag
| ^^^^^^^^^ F401
5 | from typing import Annotated
|
= help: Remove unused import: `re.RegexFlag`
Safe fix
1 1 | """Test: ensure that we treat strings in `typing.Annotation` as type definitions."""
2 2 |
3 3 | from pathlib import Path
4 |-from re import RegexFlag
5 4 | from typing import Annotated
6 5 |
7 6 | p: Annotated["Path", int] = 1