mirror of
https://github.com/astral-sh/ruff.git
synced 2025-07-24 05:25:17 +00:00
Try statements have a body: Fix formatter instability (#5558)
## Summary
The following code was previously leading to unstable formatting:
```python
try:
try:
pass
finally:
print(1) # issue7208
except A:
pass
```
The comment would be formatted as a trailing comment of `try` which is
unstable as an end-of-line comment gets two extra whitespaces.
This was originally found in
99b00efd5e/Lib/getpass.py (L68-L91)
## Test Plan
I added a regression test
This commit is contained in:
parent
25981420c4
commit
8184235f93
3 changed files with 88 additions and 76 deletions
|
@ -4281,6 +4281,8 @@ impl AnyNodeRef<'_> {
|
|||
| AnyNodeRef::StmtFunctionDef(_)
|
||||
| AnyNodeRef::StmtAsyncFunctionDef(_)
|
||||
| AnyNodeRef::StmtClassDef(_)
|
||||
| AnyNodeRef::StmtTry(_)
|
||||
| AnyNodeRef::StmtTryStar(_)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -89,3 +89,13 @@ else:
|
|||
# before finally
|
||||
finally:
|
||||
...
|
||||
|
||||
# try and try star are statements with body
|
||||
# Minimized from https://github.com/python/cpython/blob/99b00efd5edfd5b26bf9e2a35cbfc96277fdcbb1/Lib/getpass.py#L68-L91
|
||||
try:
|
||||
try:
|
||||
pass
|
||||
finally:
|
||||
print(1) # issue7208
|
||||
except A:
|
||||
pass
|
||||
|
|
|
@ -335,8 +335,11 @@ fn handle_in_between_bodies_end_of_line_comment<'a>(
|
|||
}
|
||||
|
||||
// The comment must be between two statements...
|
||||
if let (Some(preceding), Some(following)) = (comment.preceding_node(), comment.following_node())
|
||||
{
|
||||
let (Some(preceding), Some(following)) = (comment.preceding_node(), comment.following_node())
|
||||
else {
|
||||
return CommentPlacement::Default(comment);
|
||||
};
|
||||
|
||||
// ...and the following statement must be the first statement in an alternate body of the parent...
|
||||
if !is_first_statement_in_enclosing_alternate_body(following, comment.enclosing_node()) {
|
||||
// ```python
|
||||
|
@ -416,9 +419,6 @@ fn handle_in_between_bodies_end_of_line_comment<'a>(
|
|||
CommentPlacement::trailing(preceding, comment)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
CommentPlacement::Default(comment)
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles trailing comments at the end of a body block (or any other block that is indented).
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue