Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion src/docformatter/classify.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,37 @@ def is_attribute_docstring(
if not seen_equal_or_colon:
return False

return True
# Step 3: A string nested inside brackets is an argument or a collection
# element, not an attribute docstring.
return not _is_inside_brackets(tokens, index)


def _is_inside_brackets(
tokens: list[tokenize.TokenInfo],
index: int,
) -> bool:
"""Return True if the token at index sits inside an unclosed bracket.

Parameters
----------
tokens : list[TokenInfo]
A list of tokenized Python source code.
index : int
Index of the token to check.

Returns
-------
True if the token is nested inside brackets, False otherwise.
"""
depth = 0
for tok in tokens[0:index]:
if tok.type == tokenize.OP:
if tok.string in ("(", "[", "{"):
depth += 1
elif tok.string in (")", "]", "}"):
depth -= 1

return depth > 0


def is_class_docstring(
Expand Down
17 changes: 17 additions & 0 deletions tests/test_classify_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,23 @@ def test_docstring_classifiers(test_key, classifier):
assert result == expected, f"\nFailed {test_key}\nExpected {expected}\nGot {result}"


@pytest.mark.unit
@pytest.mark.parametrize(
"source",
[
'SCRIPT = textwrap.dedent(\n """\n import sys\n """\n)\n',
'MAPPING = dict(\n key="""value""",\n)\n',
'ITEMS = [\n """first""",\n]\n',
],
)
def test_is_not_attribute_docstring_inside_brackets(source):
"""A string nested in brackets is an argument, not an attribute docstring."""
tokens = get_tokens(source)
index = get_string_index(tokens)

assert not is_attribute_docstring(tokens, index)


@pytest.mark.unit
@pytest.mark.parametrize(
"test_key,classifier",
Expand Down
Loading