Skip to content

Commit

Permalink
Normalize async functions properly (tox-dev#182)
Browse files Browse the repository at this point in the history
  • Loading branch information
cblegare committed Sep 19, 2021
1 parent 05b31d6 commit 1cc8130
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
8 changes: 7 additions & 1 deletion sphinx_autodoc_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,19 @@ def remove_prefix(text, prefix):
for i, l in enumerate(sourcelines):
if l.lstrip().startswith("def"):
idx = i
whitespace_separator = "def"
break
elif l.lstrip().startswith("async def"):
idx = i
whitespace_separator = "async def"
break

else:
return "\n".join(sourcelines)
fn_def = sourcelines[idx]

# Get a string representing the amount of leading whitespace
whitespace = fn_def.split("def")[0]
whitespace = fn_def.split(whitespace_separator)[0]

# Add this leading whitespace to all lines before and after the `def`
aligned_prefix = [whitespace + remove_prefix(s, whitespace) for s in sourcelines[:idx]]
Expand Down
18 changes: 17 additions & 1 deletion tests/test_sphinx_autodoc_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from sphinx_autodoc_typehints import (
format_annotation, get_annotation_args, get_annotation_class_name, get_annotation_module,
process_docstring)
normalize_source_lines, process_docstring)

T = TypeVar('T')
U = TypeVar('U', covariant=True)
Expand Down Expand Up @@ -526,3 +526,19 @@ class dummy_module.DataClass(x)
''')
expected_contents = expected_contents.format(**format_args).replace('–', '--')
assert text_contents == expected_contents


def test_normalize_source_lines_async_def():
source = textwrap.dedent("""
async def async_function():
class InnerClass:
def __init__(self): pass
""")

expected = textwrap.dedent("""
async def async_function():
class InnerClass:
def __init__(self): pass
""")

assert normalize_source_lines(source) == expected

0 comments on commit 1cc8130

Please sign in to comment.