All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
4 from dataclasses import dataclass, field
18 from black.brackets import COMMA_PRIORITY, DOT_PRIORITY, BracketTracker
19 from black.mode import Mode, Preview
20 from black.nodes import (
29 is_one_sequence_between,
31 is_with_or_async_with_stmt,
36 from black.strings import str_width
37 from blib2to3.pgen2 import token
38 from blib2to3.pytree import Leaf, Node
44 LN = Union[Leaf, Node]
49 """Holds leaves and comments. Can be printed with `str(line)`."""
53 leaves: List[Leaf] = field(default_factory=list)
54 # keys ordered like `leaves`
55 comments: Dict[LeafID, List[Leaf]] = field(default_factory=dict)
56 bracket_tracker: BracketTracker = field(default_factory=BracketTracker)
57 inside_brackets: bool = False
58 should_split_rhs: bool = False
59 magic_trailing_comma: Optional[Leaf] = None
62 self, leaf: Leaf, preformatted: bool = False, track_bracket: bool = False
64 """Add a new `leaf` to the end of the line.
66 Unless `preformatted` is True, the `leaf` will receive a new consistent
67 whitespace prefix and metadata applied by :class:`BracketTracker`.
68 Trailing commas are maybe removed, unpacked for loop variables are
69 demoted from being delimiters.
71 Inline comments are put aside.
73 has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
77 if token.COLON == leaf.type and self.is_class_paren_empty:
79 if self.leaves and not preformatted:
80 # Note: at this point leaf.prefix should be empty except for
81 # imports, for which we only preserve newlines.
82 leaf.prefix += whitespace(
83 leaf, complex_subscript=self.is_complex_subscript(leaf)
85 if self.inside_brackets or not preformatted or track_bracket:
86 self.bracket_tracker.mark(leaf)
87 if self.mode.magic_trailing_comma:
88 if self.has_magic_trailing_comma(leaf):
89 self.magic_trailing_comma = leaf
90 elif self.has_magic_trailing_comma(leaf, ensure_removable=True):
91 self.remove_trailing_comma()
92 if not self.append_comment(leaf):
93 self.leaves.append(leaf)
95 def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
96 """Like :func:`append()` but disallow invalid standalone comment structure.
98 Raises ValueError when any `leaf` is appended after a standalone comment
99 or when a standalone comment is not the first leaf on the line.
101 if self.bracket_tracker.depth == 0:
103 raise ValueError("cannot append to standalone comments")
105 if self.leaves and leaf.type == STANDALONE_COMMENT:
107 "cannot append standalone comments to a populated line"
110 self.append(leaf, preformatted=preformatted)
113 def is_comment(self) -> bool:
114 """Is this line a standalone comment?"""
115 return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
118 def is_decorator(self) -> bool:
119 """Is this line a decorator?"""
120 return bool(self) and self.leaves[0].type == token.AT
123 def is_import(self) -> bool:
124 """Is this an import line?"""
125 return bool(self) and is_import(self.leaves[0])
128 def is_with_or_async_with_stmt(self) -> bool:
129 """Is this a with_stmt line?"""
130 return bool(self) and is_with_or_async_with_stmt(self.leaves[0])
133 def is_class(self) -> bool:
134 """Is this line a class definition?"""
137 and self.leaves[0].type == token.NAME
138 and self.leaves[0].value == "class"
142 def is_stub_class(self) -> bool:
143 """Is this line a class definition with a body consisting only of "..."?"""
144 return self.is_class and self.leaves[-3:] == [
145 Leaf(token.DOT, ".") for _ in range(3)
149 def is_def(self) -> bool:
150 """Is this a function definition? (Also returns True for async defs.)"""
152 first_leaf = self.leaves[0]
157 second_leaf: Optional[Leaf] = self.leaves[1]
160 return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
161 first_leaf.type == token.ASYNC
162 and second_leaf is not None
163 and second_leaf.type == token.NAME
164 and second_leaf.value == "def"
168 def is_class_paren_empty(self) -> bool:
169 """Is this a class with no base classes but using parentheses?
171 Those are unnecessary and should be removed.
175 and len(self.leaves) == 4
177 and self.leaves[2].type == token.LPAR
178 and self.leaves[2].value == "("
179 and self.leaves[3].type == token.RPAR
180 and self.leaves[3].value == ")"
184 def is_triple_quoted_string(self) -> bool:
185 """Is the line a triple quoted string?"""
188 and self.leaves[0].type == token.STRING
189 and self.leaves[0].value.startswith(('"""', "'''"))
193 def opens_block(self) -> bool:
194 """Does this line open a new level of indentation."""
195 if len(self.leaves) == 0:
197 return self.leaves[-1].type == token.COLON
199 def is_fmt_pass_converted(
200 self, *, first_leaf_matches: Optional[Callable[[Leaf], bool]] = None
202 """Is this line converted from fmt off/skip code?
204 If first_leaf_matches is not None, it only returns True if the first
205 leaf of converted code matches.
207 if len(self.leaves) != 1:
209 leaf = self.leaves[0]
211 leaf.type != STANDALONE_COMMENT
212 or leaf.fmt_pass_converted_first_leaf is None
215 return first_leaf_matches is None or first_leaf_matches(
216 leaf.fmt_pass_converted_first_leaf
219 def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
220 """If so, needs to be split before emitting."""
221 for leaf in self.leaves:
222 if leaf.type == STANDALONE_COMMENT and leaf.bracket_depth <= depth_limit:
227 def contains_uncollapsable_type_comments(self) -> bool:
230 last_leaf = self.leaves[-1]
231 ignored_ids.add(id(last_leaf))
232 if last_leaf.type == token.COMMA or (
233 last_leaf.type == token.RPAR and not last_leaf.value
235 # When trailing commas or optional parens are inserted by Black for
236 # consistency, comments after the previous last element are not moved
237 # (they don't have to, rendering will still be correct). So we ignore
238 # trailing commas and invisible.
239 last_leaf = self.leaves[-2]
240 ignored_ids.add(id(last_leaf))
244 # A type comment is uncollapsable if it is attached to a leaf
245 # that isn't at the end of the line (since that could cause it
246 # to get associated to a different argument) or if there are
247 # comments before it (since that could cause it to get hidden
250 for leaf_id, comments in self.comments.items():
251 for comment in comments:
252 if is_type_comment(comment):
254 not is_type_comment(comment, " ignore")
255 and leaf_id not in ignored_ids
263 def contains_unsplittable_type_ignore(self) -> bool:
267 # If a 'type: ignore' is attached to the end of a line, we
268 # can't split the line, because we can't know which of the
269 # subexpressions the ignore was meant to apply to.
271 # We only want this to apply to actual physical lines from the
272 # original source, though: we don't want the presence of a
273 # 'type: ignore' at the end of a multiline expression to
274 # justify pushing it all onto one line. Thus we
275 # (unfortunately) need to check the actual source lines and
276 # only report an unsplittable 'type: ignore' if this line was
277 # one line in the original code.
279 # Grab the first and last line numbers, skipping generated leaves
280 first_line = next((leaf.lineno for leaf in self.leaves if leaf.lineno != 0), 0)
282 (leaf.lineno for leaf in reversed(self.leaves) if leaf.lineno != 0), 0
285 if first_line == last_line:
286 # We look at the last two leaves since a comma or an
287 # invisible paren could have been added at the end of the
289 for node in self.leaves[-2:]:
290 for comment in self.comments.get(id(node), []):
291 if is_type_comment(comment, " ignore"):
296 def contains_multiline_strings(self) -> bool:
297 return any(is_multiline_string(leaf) for leaf in self.leaves)
299 def has_magic_trailing_comma(
300 self, closing: Leaf, ensure_removable: bool = False
302 """Return True if we have a magic trailing comma, that is when:
303 - there's a trailing comma here
304 - it's not a one-tuple
305 - it's not a single-element subscript
306 Additionally, if ensure_removable:
307 - it's not from square bracket indexing
308 (specifically, single-element square bracket indexing)
311 closing.type in CLOSING_BRACKETS
313 and self.leaves[-1].type == token.COMMA
317 if closing.type == token.RBRACE:
320 if closing.type == token.RSQB:
323 and closing.parent.type == syms.trailer
324 and closing.opening_bracket
325 and is_one_sequence_between(
326 closing.opening_bracket,
329 brackets=(token.LSQB, token.RSQB),
334 if not ensure_removable:
337 comma = self.leaves[-1]
338 if comma.parent is None:
341 comma.parent.type != syms.subscriptlist
342 or closing.opening_bracket is None
343 or not is_one_sequence_between(
344 closing.opening_bracket,
347 brackets=(token.LSQB, token.RSQB),
354 if closing.opening_bracket is not None and not is_one_sequence_between(
355 closing.opening_bracket, closing, self.leaves
361 def append_comment(self, comment: Leaf) -> bool:
362 """Add an inline or standalone comment to the line."""
364 comment.type == STANDALONE_COMMENT
365 and self.bracket_tracker.any_open_brackets()
370 if comment.type != token.COMMENT:
374 comment.type = STANDALONE_COMMENT
378 last_leaf = self.leaves[-1]
380 last_leaf.type == token.RPAR
381 and not last_leaf.value
383 and len(list(last_leaf.parent.leaves())) <= 3
384 and not is_type_comment(comment)
386 # Comments on an optional parens wrapping a single leaf should belong to
387 # the wrapped node except if it's a type comment. Pinning the comment like
388 # this avoids unstable formatting caused by comment migration.
389 if len(self.leaves) < 2:
390 comment.type = STANDALONE_COMMENT
394 last_leaf = self.leaves[-2]
395 self.comments.setdefault(id(last_leaf), []).append(comment)
398 def comments_after(self, leaf: Leaf) -> List[Leaf]:
399 """Generate comments that should appear directly after `leaf`."""
400 return self.comments.get(id(leaf), [])
402 def remove_trailing_comma(self) -> None:
403 """Remove the trailing comma and moves the comments attached to it."""
404 trailing_comma = self.leaves.pop()
405 trailing_comma_comments = self.comments.pop(id(trailing_comma), [])
406 self.comments.setdefault(id(self.leaves[-1]), []).extend(
407 trailing_comma_comments
410 def is_complex_subscript(self, leaf: Leaf) -> bool:
411 """Return True iff `leaf` is part of a slice with non-trivial exprs."""
412 open_lsqb = self.bracket_tracker.get_open_lsqb()
413 if open_lsqb is None:
416 subscript_start = open_lsqb.next_sibling
418 if isinstance(subscript_start, Node):
419 if subscript_start.type == syms.listmaker:
422 if subscript_start.type == syms.subscriptlist:
423 subscript_start = child_towards(subscript_start, leaf)
424 return subscript_start is not None and any(
425 n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
428 def enumerate_with_length(
429 self, reversed: bool = False
430 ) -> Iterator[Tuple[Index, Leaf, int]]:
431 """Return an enumeration of leaves with their length.
433 Stops prematurely on multiline strings and standalone comments.
436 Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
437 enumerate_reversed if reversed else enumerate,
439 for index, leaf in op(self.leaves):
440 length = len(leaf.prefix) + len(leaf.value)
441 if "\n" in leaf.value:
442 return # Multiline strings, we can't continue.
444 for comment in self.comments_after(leaf):
445 length += len(comment.value)
447 yield index, leaf, length
449 def clone(self) -> "Line":
453 inside_brackets=self.inside_brackets,
454 should_split_rhs=self.should_split_rhs,
455 magic_trailing_comma=self.magic_trailing_comma,
458 def __str__(self) -> str:
459 """Render the line."""
463 indent = " " * self.depth
464 leaves = iter(self.leaves)
466 res = f"{first.prefix}{indent}{first.value}"
469 for comment in itertools.chain.from_iterable(self.comments.values()):
474 def __bool__(self) -> bool:
475 """Return True if the line has leaves or comments."""
476 return bool(self.leaves or self.comments)
481 """Intermediate split result from a right hand split."""
486 opening_bracket: Leaf
487 closing_bracket: Leaf
492 """Class that holds information about a block of formatted lines.
494 This is introduced so that the EmptyLineTracker can look behind the standalone
495 comments and adjust their empty lines for class or def lines.
499 previous_block: Optional["LinesBlock"]
502 content_lines: List[str] = field(default_factory=list)
505 def all_lines(self) -> List[str]:
506 empty_line = str(Line(mode=self.mode))
508 [empty_line * self.before] + self.content_lines + [empty_line * self.after]
513 class EmptyLineTracker:
514 """Provides a stateful method that returns the number of potential extra
515 empty lines needed before and after the currently processed line.
517 Note: this tracker works on lines that haven't been split yet. It assumes
518 the prefix of the first leaf consists of optional newlines. Those newlines
519 are consumed by `maybe_empty_lines()` and included in the computation.
523 previous_line: Optional[Line] = None
524 previous_block: Optional[LinesBlock] = None
525 previous_defs: List[Line] = field(default_factory=list)
526 semantic_leading_comment: Optional[LinesBlock] = None
528 def maybe_empty_lines(self, current_line: Line) -> LinesBlock:
529 """Return the number of extra empty lines before and after the `current_line`.
531 This is for separating `def`, `async def` and `class` with extra empty
532 lines (two on module-level).
534 before, after = self._maybe_empty_lines(current_line)
535 previous_after = self.previous_block.after if self.previous_block else 0
537 # Black should not insert empty lines at the beginning
540 if self.previous_line is None
541 else before - previous_after
545 previous_block=self.previous_block,
546 original_line=current_line,
551 # Maintain the semantic_leading_comment state.
552 if current_line.is_comment:
553 if self.previous_line is None or (
554 not self.previous_line.is_decorator
555 # `or before` means this comment already has an empty line before
556 and (not self.previous_line.is_comment or before)
557 and (self.semantic_leading_comment is None or before)
559 self.semantic_leading_comment = block
560 # `or before` means this decorator already has an empty line before
561 elif not current_line.is_decorator or before:
562 self.semantic_leading_comment = None
564 self.previous_line = current_line
565 self.previous_block = block
568 def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
570 if current_line.depth == 0:
571 max_allowed = 1 if self.mode.is_pyi else 2
572 if current_line.leaves:
573 # Consume the first leaf's extra newlines.
574 first_leaf = current_line.leaves[0]
575 before = first_leaf.prefix.count("\n")
576 before = min(before, max_allowed)
577 first_leaf.prefix = ""
580 depth = current_line.depth
581 while self.previous_defs and self.previous_defs[-1].depth >= depth:
583 assert self.previous_line is not None
584 if depth and not current_line.is_def and self.previous_line.is_def:
585 # Empty lines between attributes and methods should be preserved.
586 before = min(1, before)
588 Preview.blank_line_after_nested_stub_class in self.mode
589 and self.previous_defs[-1].is_class
590 and not self.previous_defs[-1].is_stub_class
602 and self.previous_defs[-1].depth
603 and current_line.leaves[-1].type == token.COLON
605 current_line.leaves[0].value
606 not in ("with", "try", "for", "while", "if", "match")
609 # We shouldn't add two newlines between an indented function and
610 # a dependent non-indented clause. This is to avoid issues with
611 # conditional function definitions that are technically top-level
612 # and therefore get two trailing newlines, but look weird and
613 # inconsistent when they're followed by elif, else, etc. This is
614 # worse because these functions only get *one* preceding newline
619 self.previous_defs.pop()
620 if current_line.is_decorator or current_line.is_def or current_line.is_class:
621 return self._maybe_empty_lines_for_class_or_def(current_line, before)
625 and self.previous_line.is_import
626 and not current_line.is_import
627 and not current_line.is_fmt_pass_converted(first_leaf_matches=is_import)
628 and depth == self.previous_line.depth
630 return (before or 1), 0
634 and self.previous_line.is_class
635 and current_line.is_triple_quoted_string
639 if self.previous_line and self.previous_line.opens_block:
643 def _maybe_empty_lines_for_class_or_def(
644 self, current_line: Line, before: int
645 ) -> Tuple[int, int]:
646 if not current_line.is_decorator:
647 self.previous_defs.append(current_line)
648 if self.previous_line is None:
649 # Don't insert empty lines before the first line in the file.
652 if self.previous_line.is_decorator:
653 if self.mode.is_pyi and current_line.is_stub_class:
654 # Insert an empty line after a decorated stub class
659 if self.previous_line.depth < current_line.depth and (
660 self.previous_line.is_class or self.previous_line.is_def
664 comment_to_add_newlines: Optional[LinesBlock] = None
666 self.previous_line.is_comment
667 and self.previous_line.depth == current_line.depth
670 slc = self.semantic_leading_comment
673 and slc.previous_block is not None
674 and not slc.previous_block.original_line.is_class
675 and not slc.previous_block.original_line.opens_block
678 comment_to_add_newlines = slc
683 if current_line.is_class or self.previous_line.is_class:
684 if self.previous_line.depth < current_line.depth:
686 elif self.previous_line.depth > current_line.depth:
688 elif current_line.is_stub_class and self.previous_line.is_stub_class:
689 # No blank line between classes with an empty body
694 current_line.is_def or current_line.is_decorator
695 ) and not self.previous_line.is_def:
696 if current_line.depth:
697 # In classes empty lines between attributes and methods should
699 newlines = min(1, before)
701 # Blank line between a block of functions (maybe with preceding
702 # decorators) and a block of non-functions
704 elif self.previous_line.depth > current_line.depth:
709 newlines = 1 if current_line.depth else 2
710 if comment_to_add_newlines is not None:
711 previous_block = comment_to_add_newlines.previous_block
712 if previous_block is not None:
713 comment_to_add_newlines.before = (
714 max(comment_to_add_newlines.before, newlines) - previous_block.after
720 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
721 """Like `reversed(enumerate(sequence))` if that were possible."""
722 index = len(sequence) - 1
723 for element in reversed(sequence):
724 yield (index, element)
729 new_line: Line, old_line: Line, leaves: List[Leaf], preformatted: bool = False
732 Append leaves (taken from @old_line) to @new_line, making sure to fix the
733 underlying Node structure where appropriate.
735 All of the leaves in @leaves are duplicated. The duplicates are then
736 appended to @new_line and used to replace their originals in the underlying
737 Node structure. Any comments attached to the old leaves are reattached to
741 set(@leaves) is a subset of set(@old_line.leaves).
743 for old_leaf in leaves:
744 new_leaf = Leaf(old_leaf.type, old_leaf.value)
745 replace_child(old_leaf, new_leaf)
746 new_line.append(new_leaf, preformatted=preformatted)
748 for comment_leaf in old_line.comments_after(old_leaf):
749 new_line.append(comment_leaf, preformatted=True)
752 def is_line_short_enough( # noqa: C901
753 line: Line, *, mode: Mode, line_str: str = ""
755 """For non-multiline strings, return True if `line` is no longer than `line_length`.
756 For multiline strings, looks at the context around `line` to determine
757 if it should be inlined or split up.
758 Uses the provided `line_str` rendering, if any, otherwise computes a new one.
761 line_str = line_to_string(line)
763 width = str_width if mode.preview else len
765 if Preview.multiline_string_handling not in mode:
767 width(line_str) <= mode.line_length
768 and "\n" not in line_str # multiline strings
769 and not line.contains_standalone_comments()
772 if line.contains_standalone_comments():
774 if "\n" not in line_str:
775 # No multiline strings (MLS) present
776 return width(line_str) <= mode.line_length
778 first, *_, last = line_str.split("\n")
779 if width(first) > mode.line_length or width(last) > mode.line_length:
782 # Traverse the AST to examine the context of the multiline string (MLS),
783 # tracking aspects such as depth and comma existence,
784 # to determine whether to split the MLS or keep it together.
785 # Depth (which is based on the existing bracket_depth concept)
786 # is needed to determine nesting level of the MLS.
787 # Includes special case for trailing commas.
788 commas: List[int] = [] # tracks number of commas per depth level
789 multiline_string: Optional[Leaf] = None
790 # store the leaves that contain parts of the MLS
791 multiline_string_contexts: List[LN] = []
793 max_level_to_update = math.inf # track the depth of the MLS
794 for i, leaf in enumerate(line.leaves):
795 if max_level_to_update == math.inf:
796 had_comma: Optional[int] = None
797 if leaf.bracket_depth + 1 > len(commas):
799 elif leaf.bracket_depth + 1 < len(commas):
800 had_comma = commas.pop()
802 had_comma is not None
803 and multiline_string is not None
804 and multiline_string.bracket_depth == leaf.bracket_depth + 1
806 # Have left the level with the MLS, stop tracking commas
807 max_level_to_update = leaf.bracket_depth
809 # MLS was in parens with at least one comma - force split
812 if leaf.bracket_depth <= max_level_to_update and leaf.type == token.COMMA:
813 # Ignore non-nested trailing comma
814 # directly after MLS/MLS-containing expression
815 ignore_ctxs: List[Optional[LN]] = [None]
816 ignore_ctxs += multiline_string_contexts
817 if not (leaf.prev_sibling in ignore_ctxs and i == len(line.leaves) - 1):
818 commas[leaf.bracket_depth] += 1
819 if max_level_to_update != math.inf:
820 max_level_to_update = min(max_level_to_update, leaf.bracket_depth)
822 if is_multiline_string(leaf):
823 if len(multiline_string_contexts) > 0:
824 # >1 multiline string cannot fit on a single line - force split
826 multiline_string = leaf
828 # fetch the leaf components of the MLS in the AST
829 while str(ctx) in line_str:
830 multiline_string_contexts.append(ctx)
831 if ctx.parent is None:
835 # May not have a triple-quoted multiline string at all,
836 # in case of a regular string with embedded newlines and line continuations
837 if len(multiline_string_contexts) == 0:
840 return all(val == 0 for val in commas)
843 def can_be_split(line: Line) -> bool:
844 """Return False if the line cannot be split *for sure*.
846 This is not an exhaustive search but a cheap heuristic that we can use to
847 avoid some unfortunate formattings (mostly around wrapping unsplittable code
848 in unnecessary parentheses).
854 if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
858 for leaf in leaves[-2::-1]:
859 if leaf.type in OPENING_BRACKETS:
860 if next.type not in CLOSING_BRACKETS:
864 elif leaf.type == token.DOT:
866 elif leaf.type == token.NAME:
867 if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
870 elif leaf.type not in CLOSING_BRACKETS:
873 if dot_count > 1 and call_count > 1:
879 def can_omit_invisible_parens(
883 """Does `rhs.body` have a shape safe to reformat without optional parens around it?
885 Returns True for only a subset of potentially nice looking formattings but
886 the point is to not return false positives that end up producing lines that
890 bt = line.bracket_tracker
891 if not bt.delimiters:
892 # Without delimiters the optional parentheses are useless.
895 max_priority = bt.max_delimiter_priority()
896 delimiter_count = bt.delimiter_count_with_priority(max_priority)
897 if delimiter_count > 1:
898 # With more than one delimiter of a kind the optional parentheses read better.
901 if delimiter_count == 1:
903 Preview.wrap_multiple_context_managers_in_parens in line.mode
904 and max_priority == COMMA_PRIORITY
905 and rhs.head.is_with_or_async_with_stmt
907 # For two context manager with statements, the optional parentheses read
908 # better. In this case, `rhs.body` is the context managers part of
909 # the with statement. `rhs.head` is the `with (` part on the previous
912 # Otherwise it may also read better, but we don't do it today and requires
913 # careful considerations for all possible cases. See
914 # https://github.com/psf/black/issues/2156.
916 if max_priority == DOT_PRIORITY:
917 # A single stranded method call doesn't require optional parentheses.
920 assert len(line.leaves) >= 2, "Stranded delimiter"
922 # With a single delimiter, omit if the expression starts or ends with
924 first = line.leaves[0]
925 second = line.leaves[1]
926 if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
927 if _can_omit_opening_paren(line, first=first, line_length=line_length):
930 # Note: we are not returning False here because a line might have *both*
931 # a leading opening bracket and a trailing closing bracket. If the
932 # opening bracket doesn't match our rule, maybe the closing will.
934 penultimate = line.leaves[-2]
935 last = line.leaves[-1]
938 last.type == token.RPAR
939 or last.type == token.RBRACE
941 # don't use indexing for omitting optional parentheses;
943 last.type == token.RSQB
945 and last.parent.type != syms.trailer
948 if penultimate.type in OPENING_BRACKETS:
949 # Empty brackets don't help.
952 if is_multiline_string(first):
953 # Additional wrapping of a multiline string in this situation is
957 if _can_omit_closing_paren(line, last=last, line_length=line_length):
963 def _can_omit_opening_paren(line: Line, *, first: Leaf, line_length: int) -> bool:
964 """See `can_omit_invisible_parens`."""
966 length = 4 * line.depth
968 for _index, leaf, leaf_length in line.enumerate_with_length():
969 if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
972 length += leaf_length
973 if length > line_length:
976 if leaf.type in OPENING_BRACKETS:
977 # There are brackets we can further split on.
981 # checked the entire string and line length wasn't exceeded
982 if len(line.leaves) == _index + 1:
988 def _can_omit_closing_paren(line: Line, *, last: Leaf, line_length: int) -> bool:
989 """See `can_omit_invisible_parens`."""
990 length = 4 * line.depth
991 seen_other_brackets = False
992 for _index, leaf, leaf_length in line.enumerate_with_length():
993 length += leaf_length
994 if leaf is last.opening_bracket:
995 if seen_other_brackets or length <= line_length:
998 elif leaf.type in OPENING_BRACKETS:
999 # There are brackets we can further split on.
1000 seen_other_brackets = True
1005 def line_to_string(line: Line) -> str:
1006 """Returns the string representation of @line.
1008 WARNING: This is known to be computationally expensive.
1010 return str(line).strip("\n")