From 7d062ecd5f14124a99daf452c46054ada656ad8b Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Mon, 12 Dec 2022 20:56:38 -0800 Subject: [PATCH] Do not put the closing quotes in a docstring on a separate line (#3430) Fixes #3320. Followup from #3044. --- CHANGES.md | 2 ++ src/black/linegen.py | 13 ++++++------- tests/data/preview/docstring_preview.py | 6 ++---- 3 files changed, 10 insertions(+), 11 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 86d44f033b8..f6040359623 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -15,6 +15,8 @@ - Fix a crash in preview style with assert + parenthesized string (#3415) +- Do not put the closing quotes in a docstring on a separate line, even if the line is + too long (#3430) ### Configuration diff --git a/src/black/linegen.py b/src/black/linegen.py index 219495e9a5e..644824a3c86 100644 --- a/src/black/linegen.py +++ b/src/black/linegen.py @@ -389,19 +389,18 @@ def visit_STRING(self, leaf: Leaf) -> Iterator[Line]: # We need to find the length of the last line of the docstring # to find if we can add the closing quotes to the line without # exceeding the maximum line length. - # If docstring is one line, then we need to add the length - # of the indent, prefix, and starting quotes. Ending quotes are - # handled later. + # If docstring is one line, we don't put the closing quotes on a + # separate line because it looks ugly (#3320). lines = docstring.splitlines() last_line_length = len(lines[-1]) if docstring else 0 - if len(lines) == 1: - last_line_length += len(indent) + len(prefix) + quote_len - # If adding closing quotes would cause the last line to exceed # the maximum line length then put a line break before the # closing quotes - if last_line_length + quote_len > self.mode.line_length: + if ( + len(lines) > 1 + and last_line_length + quote_len > self.mode.line_length + ): leaf.value = prefix + quote + docstring + "\n" + indent + quote else: leaf.value = prefix + quote + docstring + quote diff --git a/tests/data/preview/docstring_preview.py b/tests/data/preview/docstring_preview.py index 292352c82f3..ff4819acb67 100644 --- a/tests/data/preview/docstring_preview.py +++ b/tests/data/preview/docstring_preview.py @@ -54,13 +54,11 @@ def single_quote_docstring_over_line_limit2(): def docstring_almost_at_line_limit(): - """long docstring................................................................. - """ + """long docstring.................................................................""" def docstring_almost_at_line_limit_with_prefix(): - f"""long docstring................................................................ - """ + f"""long docstring................................................................""" def mulitline_docstring_almost_at_line_limit():