|
1 | 1 | import itertools |
2 | 2 | import math |
3 | | -import sys |
4 | 3 | from dataclasses import dataclass, field |
5 | 4 | from typing import ( |
6 | 5 | Callable, |
@@ -103,7 +102,10 @@ def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None: |
103 | 102 | Raises ValueError when any `leaf` is appended after a standalone comment |
104 | 103 | or when a standalone comment is not the first leaf on the line. |
105 | 104 | """ |
106 | | - if self.bracket_tracker.depth == 0: |
| 105 | + if ( |
| 106 | + self.bracket_tracker.depth == 0 |
| 107 | + or self.bracket_tracker.any_open_for_or_lambda() |
| 108 | + ): |
107 | 109 | if self.is_comment: |
108 | 110 | raise ValueError("cannot append to standalone comments") |
109 | 111 |
|
@@ -233,10 +235,10 @@ def is_fmt_pass_converted( |
233 | 235 | leaf.fmt_pass_converted_first_leaf |
234 | 236 | ) |
235 | 237 |
|
236 | | - def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool: |
| 238 | + def contains_standalone_comments(self) -> bool: |
237 | 239 | """If so, needs to be split before emitting.""" |
238 | 240 | for leaf in self.leaves: |
239 | | - if leaf.type == STANDALONE_COMMENT and leaf.bracket_depth <= depth_limit: |
| 241 | + if leaf.type == STANDALONE_COMMENT: |
240 | 242 | return True |
241 | 243 |
|
242 | 244 | return False |
@@ -982,6 +984,23 @@ def can_omit_invisible_parens( |
982 | 984 | are too long. |
983 | 985 | """ |
984 | 986 | line = rhs.body |
| 987 | + |
| 988 | + # We need optional parens in order to split standalone comments to their own lines |
| 989 | + # if there are no nested parens around the standalone comments |
| 990 | + closing_bracket: Optional[Leaf] = None |
| 991 | + for leaf in reversed(line.leaves): |
| 992 | + if closing_bracket and leaf is closing_bracket.opening_bracket: |
| 993 | + closing_bracket = None |
| 994 | + if leaf.type == STANDALONE_COMMENT and not closing_bracket: |
| 995 | + return False |
| 996 | + if ( |
| 997 | + not closing_bracket |
| 998 | + and leaf.type in CLOSING_BRACKETS |
| 999 | + and leaf.opening_bracket in line.leaves |
| 1000 | + and leaf.value |
| 1001 | + ): |
| 1002 | + closing_bracket = leaf |
| 1003 | + |
985 | 1004 | bt = line.bracket_tracker |
986 | 1005 | if not bt.delimiters: |
987 | 1006 | # Without delimiters the optional parentheses are useless. |
|
0 commit comments