Skip to content

Commit 685512d

Browse files
committed
fix: Format signatures with full-path names
1 parent 40077f9 commit 685512d

File tree

2 files changed

+40
-9
lines changed

2 files changed

+40
-9
lines changed

src/mkdocstrings_handlers/python/rendering.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,18 @@ def do_format_signature(signature: str, line_length: int) -> str:
7373
code = signature.strip()
7474
if len(code) < line_length:
7575
return code
76+
77+
# Black cannot format names with dots, so we replace
78+
# the whole name with a string of equal length
79+
name_length = code.index("(")
80+
name = code[:name_length]
7681
formatter = _get_black_formatter()
77-
formatted = formatter(f"def {code}: pass", line_length)
78-
# remove starting `def ` and trailing `: pass`
79-
return formatted[4:-5].strip()[:-1]
82+
formatable = f"def {'x' * name_length}{code[name_length:]}: pass"
83+
formatted = formatter(formatable, line_length)
84+
85+
# We put back the original name
86+
# and remove starting `def ` and trailing `: pass`
87+
return name + formatted[4:-5].strip()[name_length:-1]
8088

8189

8290
def do_order_members(

tests/test_rendering.py

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,35 @@
1111
from mkdocstrings_handlers.python import rendering
1212

1313

14-
def test_format_code_and_signature() -> None:
15-
"""Assert code and signatures can be Black-formatted."""
16-
assert rendering.do_format_code("print('Hello')", 100)
17-
assert rendering.do_format_code('print("Hello")', 100)
18-
assert rendering.do_format_signature("(param: str = 'hello') -> 'Class'", 100)
19-
assert rendering.do_format_signature('(param: str = "hello") -> "Class"', 100)
14+
@pytest.mark.parametrize(
15+
"code",
16+
[
17+
"print('Hello')",
18+
"aaaaa(bbbbb, ccccc=1) + ddddd.eeeee[ffff] or {ggggg: hhhhh, iiiii: jjjjj}",
19+
],
20+
)
21+
def test_format_code(code: str) -> None:
22+
"""Assert code can be Black-formatted.
23+
24+
Parameters:
25+
code: Code to format.
26+
"""
27+
for length in (5, 100):
28+
assert rendering.do_format_code(code, length)
29+
30+
31+
@pytest.mark.parametrize(
32+
"signature",
33+
["Class.method(param: str = 'hello') -> 'OtherClass'"],
34+
)
35+
def test_format_signature(signature: str) -> None:
36+
"""Assert signatures can be Black-formatted.
37+
38+
Parameters:
39+
signature: Signature to format.
40+
"""
41+
for length in (5, 100):
42+
assert rendering.do_format_signature(signature, length)
2043

2144

2245
@dataclass

0 commit comments

Comments
 (0)