Skip to content

Commit

Permalink
Put rtype before examples or usage section (#290)
Browse files Browse the repository at this point in the history
Sometimes a function's documentation will contain a section like
'Usage' or 'Examples', warnings about edge cases, etc. These
sections are introduced with a .. directive::. This makes it so
that sphinx-autodoc-typehints inserts the return type ahead of
these sections, rather than after them.
  • Loading branch information
hoodmane committed Jan 15, 2023
1 parent a599552 commit 4ab116d
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/sphinx_autodoc_typehints/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,10 @@ def _inject_types_to_docstring(
insert_index = None
break
insert_index = at
elif line.startswith(".."):
# Make sure that rtype comes before any usage or examples section
insert_index = at
break

if insert_index is not None and app.config.typehints_document_rtype:
if insert_index == len(lines): # ensure that :rtype: doesn't get joined with a paragraph of text
Expand Down
10 changes: 10 additions & 0 deletions tests/roots/test-dummy/dummy_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,3 +276,13 @@ def mocked_import(x: Mailbox): # noqa: U100
:param x: function
"""


def func_with_examples() -> int:
"""
A docstring.
.. rubric:: Examples
Here are a couple of examples of how to use this function.
"""
2 changes: 2 additions & 0 deletions tests/roots/test-dummy/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,5 @@ Dummy Module
.. autodecorator:: dummy_module.Decorator

.. autofunction:: dummy_module.mocked_import

.. autofunction:: dummy_module.func_with_examples
11 changes: 11 additions & 0 deletions tests/test_sphinx_autodoc_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,17 @@ class dummy_module.DataClass(x)
Parameters:
**x** ("Mailbox") -- function
dummy_module.func_with_examples()
A docstring.
Return type:
"int"
-[ Examples ]-
Here are a couple of examples of how to use this function.
"""
expected_contents = dedent(expected_contents).format(**format_args).replace("–", "--")
assert text_contents == maybe_fix_py310(expected_contents)
Expand Down

0 comments on commit 4ab116d

Please sign in to comment.