Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bytes strings being treated as docstrings #4003

Merged
merged 3 commits into from Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGES.md
Expand Up @@ -8,7 +8,7 @@

### Stable style

<!-- Changes that affect Black's stable style -->
- Fix crash on formatting bytes strings that look like docstrings (#4003)

### Preview style

Expand Down
9 changes: 8 additions & 1 deletion src/black/nodes.py
Expand Up @@ -14,7 +14,7 @@

from black.cache import CACHE_DIR
from black.mode import Mode, Preview
from black.strings import has_triple_quotes
from black.strings import get_string_prefix, has_triple_quotes
from blib2to3 import pygram
from blib2to3.pgen2 import token
from blib2to3.pytree import NL, Leaf, Node, type_repr
Expand Down Expand Up @@ -525,6 +525,13 @@ def is_arith_like(node: LN) -> bool:


def is_docstring(leaf: Leaf) -> bool:
if leaf.type != token.STRING:
return False

prefix = get_string_prefix(leaf.value)
if "b" in prefix or "B" in prefix:
return False

if prev_siblings_are(
leaf.parent, [None, token.NEWLINE, token.INDENT, syms.simple_stmt]
):
Expand Down
34 changes: 34 additions & 0 deletions tests/data/cases/bytes_docstring.py
@@ -0,0 +1,34 @@
def bitey():
b" not a docstring"

def bitey2():
b' also not a docstring'

def triple_quoted_bytes():
b""" not a docstring"""

def triple_quoted_bytes2():
b''' also not a docstring'''

def capitalized_bytes():
B" NOT A DOCSTRING"

# output
def bitey():
b" not a docstring"


def bitey2():
b" also not a docstring"


def triple_quoted_bytes():
b""" not a docstring"""


def triple_quoted_bytes2():
b""" also not a docstring"""


def capitalized_bytes():
b" NOT A DOCSTRING"
File renamed without changes.