[refurb] Fix annotated assignments blocking FURB101 fix (FURB101)
#21278
+77
−11
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Fixed FURB101 (
read-whole-file) to handle annotated assignments. Previously, the rule would detect violations in code likecontents: str = f.read()but fail to generate a fix. Now it correctly generates fixes that preserve type annotations (e.g.,contents: str = Path("file.txt").read_text(encoding="utf-8")).Fixes #21274
Problem Analysis
The FURB101 rule was only checking for
Stmt::Assignstatements when determining whether a fix could be applied. When encountering annotated assignments (Stmt::AnnAssign) likecontents: str = f.read(), the rule would:visit_exprmethod only matchedStmt::Assign, notStmt::AnnAssigngenerate_fixfunction only acceptedStmt::Assignin its body validationThis occurred because Python's AST represents annotated assignments as a different node type (
StmtAnnAssign) with separate fields for the target, annotation, and value, unlike regular assignments which use a list of targets.Approach
The fix extends the rule to handle both assignment types:
Updated
visit_exprmethod: Now matches bothStmt::AssignandStmt::AnnAssign, extracting:Updated
generate_fixfunction:annotation: Option<String>parameter to accept annotation codeStmt::AssignandStmt::AnnAssign{var}: {annotation} = {binding}({filename_code}).{suggestion}Added test case: Added an annotated assignment test case to verify the fix works correctly.
The implementation maintains backward compatibility with regular assignments while adding support for annotated assignments, ensuring type annotations are preserved in the generated fixes.