def append_comment(self, comment: Leaf) -> bool: """Add an inline or standalone comment to the line.""" if (comment.type == STANDALONE_COMMENT and self.bracket_tracker.any_open_brackets()): comment.prefix = "" return False if comment.type != token.COMMENT: return False if not self.leaves: comment.type = STANDALONE_COMMENT comment.prefix = "" return False last_leaf = self.leaves[-1] if (last_leaf.type == token.RPAR and not last_leaf.value and last_leaf.parent and len(list(last_leaf.parent.leaves())) <= 3 and not is_type_comment(comment)): # Comments on an optional parens wrapping a single leaf should belong to # the wrapped node except if it's a type comment. Pinning the comment like # this avoids unstable formatting caused by comment migration. if len(self.leaves) < 2: comment.type = STANDALONE_COMMENT comment.prefix = "" return False last_leaf = self.leaves[-2] self.comments.setdefault(id(last_leaf), []).append(comment) return True
def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool: """Hack a standalone comment to act as a trailing comment for line splitting. If this line has brackets and a standalone `comment`, we need to adapt it to be able to still reformat the line. This is not perfect, the line to which the standalone comment gets appended will appear "too long" when splitting. """ if not (comment.type == STANDALONE_COMMENT and self.bracket_tracker.any_open_brackets()): return False comment.type = token.COMMENT comment.prefix = '\n' + ' ' * (self.depth + 1) return self.append_comment(comment)
def append_comment(self, comment: Leaf) -> bool: if comment.type != token.COMMENT: return False try: after = id(self.last_non_delimiter()) except LookupError: comment.type = STANDALONE_COMMENT comment.prefix = '' return False else: if after in self.comments: self.comments[after].value += str(comment) else: self.comments[after] = comment return True