mirror of
https://github.com/astral-sh/ruff.git
synced 2025-11-23 13:36:52 +00:00
Avoid syntax error when formatting attribute expressions with outer parentheses, parenthesized value, and trailing comment on value (#20418)
Closes #19350 This fixes a syntax error caused by formatting. However, the new tests reveal that there are some cases where formatting attributes with certain comments behaves strangely, both before and after this PR, so some more polish may be in order. For example, without parentheses around the value, and both before and after this PR, we have: ```python # unformatted variable = ( something # a comment .first_method("some string") ) # formatted variable = something.first_method("some string") # a comment ``` which is probably not where the comment ought to go.
This commit is contained in:
parent
d063c71177
commit
8156b45173
3 changed files with 166 additions and 1 deletions
|
|
@ -179,7 +179,22 @@ impl NeedsParentheses for ExprAttribute {
|
|||
context.comments().ranges(),
|
||||
context.source(),
|
||||
) {
|
||||
OptionalParentheses::Never
|
||||
// We have to avoid creating syntax errors like
|
||||
// ```python
|
||||
// variable = (something) # trailing
|
||||
// .my_attribute
|
||||
// ```
|
||||
// See https://github.com/astral-sh/ruff/issues/19350
|
||||
if context
|
||||
.comments()
|
||||
.trailing(self.value.as_ref())
|
||||
.iter()
|
||||
.any(|comment| comment.line_position().is_end_of_line())
|
||||
{
|
||||
OptionalParentheses::Multiline
|
||||
} else {
|
||||
OptionalParentheses::Never
|
||||
}
|
||||
} else {
|
||||
self.value.needs_parentheses(self.into(), context)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue