[isort] Fix inserting required imports before future imports (I002)#20676
[isort] Fix inserting required imports before future imports (I002)#20676ntBre merged 7 commits intoastral-sh:mainfrom
isort] Fix inserting required imports before future imports (I002)#20676Conversation
|
| self.python_ast.iter().rev().find(|stmt| { | ||
| if let Stmt::ImportFrom(import_from) = stmt { | ||
| import_from.module.as_deref() == Some("__future__") | ||
| } else { | ||
| false | ||
| } | ||
| }) |
There was a problem hiding this comment.
Since future imports can only be at the beginning, iterating over all statements is inefficient, particularly on large files with many statements. Instead, only look through statements until you've found something that's not a future import.
Eg, something like:
fn find_last_future_import(&self) -> Option<&'a Stmt> {
self.python_ast.iter().take_while(|stmt| {
if let Stmt::ImportFrom(import_from) = stmt {
import_from.module.as_deref() == Some("__future__")
} else {
false
}
}).last()
}
...es/isort/snapshots/ruff_linter__rules__isort__tests__required_import_existing_import.py.snap
Show resolved
Hide resolved
| false | ||
| } | ||
| }) | ||
| .last() |
There was a problem hiding this comment.
I think we could take some inspiration from the match_docstring_end helper and just skip one statement. It's not a huge deal since something like this is a separate syntax error, but it still seems a bit more precise:
"docstring"
"another string"
from __future__ import annotations # SyntaxError: from __future__ imports must occur at the beginning of the fileWhat do you think about something like this?
/// Find the last valid `from __future__` import statement in the AST.
fn find_last_future_import(&self) -> Option<&'a Stmt> {
let mut body = self.python_ast.iter().peekable();
let _docstring = body.next_if(|stmt| is_docstring_stmt(stmt));
body.take_while(|stmt| {
stmt.as_import_from_stmt()
.is_some_and(|import_from| import_from.module.as_deref() == Some("__future__"))
})
.last()
}| Ok(()) | ||
| } | ||
|
|
||
| #[test_case(Path::new("docstring_future_import.py"))] |
There was a problem hiding this comment.
Can we make these two test_cases on the same test function? The bodies of the functions look pretty much the same to me, besides the snapshot name. I think using the test case path is enough differentiation in the filename, though.
…ng_future_import_docstring_future_import.py.snap
Summary
Fixes #20674