mirror of
https://github.com/astral-sh/ruff.git
synced 2025-07-23 04:55:09 +00:00
Treat comments on open parentheses in return annotations as dangling (#6413)
## Summary Given: ```python def double(a: int) -> ( # Hello int ): return 2*a ``` We currently treat `# Hello` as a trailing comment on the parameters (`(a: int)`). This PR adds a placement method to instead treat it as a dangling comment on the function definition itself, so that it gets formatted at the end of the definition, like: ```python def double(a: int) -> int: # Hello return 2*a ``` The formatting in this case is unchanged, but it's incorrect IMO for that to be a trailing comment on the parameters, and that placement leads to an instability after changing the grouping in #6410. Fixing this led to a _different_ instability related to tuple return type annotations, like: ```python def zrevrangebylex(self, name: _Key, max: _Value, min: _Value, start: int | None = None, num: int | None = None) -> ( # type: ignore[override] ): ... ``` (This is a real example.) To fix, I had to special-case tuples in that spot, though I'm not certain that's correct.
This commit is contained in:
parent
d33618062e
commit
55d6fd53cd
4 changed files with 211 additions and 12 deletions
|
@ -61,17 +61,20 @@ impl FormatNodeRule<StmtFunctionDef> for FormatStmtFunctionDef {
|
|||
write!(f, [item.parameters.format()])?;
|
||||
|
||||
if let Some(return_annotation) = item.returns.as_ref() {
|
||||
write!(
|
||||
f,
|
||||
[
|
||||
space(),
|
||||
text("->"),
|
||||
space(),
|
||||
optional_parentheses(
|
||||
&return_annotation.format().with_options(Parentheses::Never)
|
||||
)
|
||||
]
|
||||
)?;
|
||||
write!(f, [space(), text("->"), space()])?;
|
||||
if return_annotation.is_tuple_expr() {
|
||||
write!(
|
||||
f,
|
||||
[return_annotation.format().with_options(Parentheses::Never)]
|
||||
)?;
|
||||
} else {
|
||||
write!(
|
||||
f,
|
||||
[optional_parentheses(
|
||||
&return_annotation.format().with_options(Parentheses::Never),
|
||||
)]
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
write!(
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue