From e50110353ab81b539aaee686453c18c707b5f045 Mon Sep 17 00:00:00 2001 From: Henri Holopainen Date: Tue, 31 Oct 2023 17:27:11 +0200 Subject: [PATCH] Produce equivalent code for docstrings containing backslash followed by whitespace(s) before newline (#4008) Fixes #3727 --- CHANGES.md | 3 ++- src/black/linegen.py | 3 ++- tests/data/cases/docstring.py | 13 +++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index dd5f52cf706..e910fbed162 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -8,7 +8,8 @@ ### Stable style - +- Fix a crash when whitespace(s) followed a backslash before newline in a docstring + (#4008) ### Preview style diff --git a/src/black/linegen.py b/src/black/linegen.py index 43bc08efbbd..121c6e314fe 100644 --- a/src/black/linegen.py +++ b/src/black/linegen.py @@ -2,6 +2,7 @@ Generating lines of code. """ +import re import sys from dataclasses import replace from enum import Enum, auto @@ -420,7 +421,7 @@ def visit_STRING(self, leaf: Leaf) -> Iterator[Line]: if Preview.hex_codes_in_unicode_sequences in self.mode: normalize_unicode_escape_sequences(leaf) - if is_docstring(leaf) and "\\\n" not in leaf.value: + if is_docstring(leaf) and not re.search(r"\\\s*\n", leaf.value): # We're ignoring docstrings with backslash newline escapes because changing # indentation of those changes the AST representation of the code. if self.mode.string_normalization: diff --git a/tests/data/cases/docstring.py b/tests/data/cases/docstring.py index c31d6a68783..e983c5bd438 100644 --- a/tests/data/cases/docstring.py +++ b/tests/data/cases/docstring.py @@ -221,6 +221,12 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self): ''' +def foo(): + """ + Docstring with a backslash followed by a space\ + and then another line + """ + # output class MyClass: @@ -442,3 +448,10 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self): """ + + +def foo(): + """ + Docstring with a backslash followed by a space\ + and then another line + """