Skip to content

Commit 8a90d57

Browse files
authored
Fix placement of return type when there is a doctest (#482)
Resolves #480
1 parent 8c8c73d commit 8a90d57

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/sphinx_autodoc_typehints/patches.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
from functools import lru_cache
66
from typing import TYPE_CHECKING, Any
77

8+
from docutils import nodes
89
from docutils.parsers.rst.directives.admonitions import BaseAdmonition
9-
from docutils.parsers.rst.states import Text
10+
from docutils.parsers.rst.states import Body, Text
1011
from sphinx.ext.napoleon.docstring import GoogleDocstring
1112

1213
from .attributes_patch import patch_attribute_handling
@@ -110,6 +111,17 @@ def _patched_text_indent(self: Text, *args: Any) -> Any:
110111
return result
111112

112113

114+
def _patched_body_doctest(
115+
self: Body, _match: None, _context: None, next_state: str | None
116+
) -> tuple[list[Any], str | None, list[Any]]:
117+
line = self.document.current_line + 1
118+
data = "\n".join(self.state_machine.get_text_block())
119+
n = nodes.doctest_block(data, data)
120+
n.line = line
121+
self.parent += n
122+
return [], next_state, []
123+
124+
113125
def _patch_line_numbers() -> None:
114126
"""
115127
Make the rst parser put line numbers on more nodes.
@@ -118,6 +130,7 @@ def _patch_line_numbers() -> None:
118130
"""
119131
Text.indent = _patched_text_indent
120132
BaseAdmonition.run = _patched_base_admonition_run
133+
Body.doctest = _patched_body_doctest
121134

122135

123136
def install_patches(app: Sphinx) -> None:

tests/test_integration.py

+26
Original file line numberDiff line numberDiff line change
@@ -1359,6 +1359,32 @@ def docstring_with_see_also() -> str:
13591359
return ""
13601360

13611361

1362+
@expected(
1363+
"""
1364+
mod.has_doctest1()
1365+
1366+
Test that we place the return type correctly when the function has
1367+
a doctest.
1368+
1369+
Return type:
1370+
"None"
1371+
1372+
>>> this is a fake doctest
1373+
a
1374+
>>> more doctest
1375+
b
1376+
"""
1377+
)
1378+
def has_doctest1() -> None:
1379+
r"""Test that we place the return type correctly when the function has a doctest.
1380+
1381+
>>> this is a fake doctest
1382+
a
1383+
>>> more doctest
1384+
b
1385+
"""
1386+
1387+
13621388
# Config settings for each test run.
13631389
# Config Name: Sphinx Options as Dict.
13641390
configs = {

0 commit comments

Comments
 (0)