Skip to content

Commit

Permalink
fix: Show correct docstring line numbers on Python 3.7
Browse files Browse the repository at this point in the history
Issue #98: #98
  • Loading branch information
pawamoy committed Sep 22, 2022
1 parent 586d7da commit edd4b6d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/griffe/agents/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,15 @@ def get_docstring(
if isinstance(doc, NodeConstant) and isinstance(doc.value, str):
return doc.value, doc.lineno, doc.end_lineno # type: ignore[attr-defined]
if isinstance(doc, NodeStr):
return doc.s, doc.lineno, doc.end_lineno # type: ignore[attr-defined]

# TODO: remove once Python 3.7 support is dropped
# on Python 3.7, lineno seems to be the ending line of the string
# rather than the starting one, so we substract the number of newlines
lineno = doc.lineno
if sys.version_info < (3, 8):
lineno -= doc.s.count("\n")

return doc.s, lineno, doc.end_lineno # type: ignore[attr-defined]
return None, None, None


Expand Down
23 changes: 22 additions & 1 deletion tests/test_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,6 @@ def test_parse_complex__all__assignments(statements):
assert package.exports == {"CONST_INIT", "CONST_A", "CONST_B", "CONST_C"}


# issue https://github.com/mkdocstrings/griffe/issues/68
def test_dont_crash_on_nested_functions_in_init():
"""Assert we don't crash when visiting a nested function in `__init__` methods."""
with temporary_visited_module(
Expand All @@ -239,3 +238,25 @@ def pl(i: int):
"""
) as module:
assert module


def test_get_correct_docstring_starting_line_number():
"""Assert we get the correct line numbers for docstring, even on Python 3.7."""
with temporary_visited_module(
"""
'''
Module docstring.
'''
class C:
'''
Class docstring.
'''
def method(self):
'''
Method docstring.
'''
"""
) as module:
assert module.docstring.lineno == 2
assert module["C"].docstring.lineno == 6
assert module["C.method"].docstring.lineno == 10

0 comments on commit edd4b6d

Please # to comment.