|
58 | 58 | import re |
59 | 59 | import sys |
60 | 60 | import warnings |
| 61 | +from inspect import Parameter |
61 | 62 | from os import path |
62 | 63 | from types import ModuleType |
63 | 64 | from typing import Any, Dict, List, Optional, Tuple, Type, cast |
|
87 | 88 | from sphinx.util import logging, rst |
88 | 89 | from sphinx.util.docutils import (NullReporter, SphinxDirective, SphinxRole, new_document, |
89 | 90 | switch_source_input) |
| 91 | +from sphinx.util.inspect import signature_from_str |
90 | 92 | from sphinx.util.matching import Matcher |
91 | 93 | from sphinx.util.typing import OptionSpec |
92 | 94 | from sphinx.writers.html import HTMLTranslator |
@@ -456,10 +458,32 @@ def strip_arg_typehint(s: str) -> str: |
456 | 458 | return s.split(':')[0].strip() |
457 | 459 |
|
458 | 460 |
|
| 461 | +def _cleanup_signature(s: str) -> str: |
| 462 | + """Clean up signature using inspect.signautre() for mangle_signature()""" |
| 463 | + try: |
| 464 | + sig = signature_from_str(s) |
| 465 | + parameters = list(sig.parameters.values()) |
| 466 | + for i, param in enumerate(parameters): |
| 467 | + if param.annotation is not Parameter.empty: |
| 468 | + # Remove typehints |
| 469 | + param = param.replace(annotation=Parameter.empty) |
| 470 | + if param.default is not Parameter.empty: |
| 471 | + # Replace default value by "None" |
| 472 | + param = param.replace(default=None) |
| 473 | + parameters[i] = param |
| 474 | + sig = sig.replace(parameters=parameters, return_annotation=Parameter.empty) |
| 475 | + return str(sig) |
| 476 | + except Exception: |
| 477 | + # Return the original signature string if failed to clean (ex. parsing error) |
| 478 | + return s |
| 479 | + |
| 480 | + |
459 | 481 | def mangle_signature(sig: str, max_chars: int = 30) -> str: |
460 | 482 | """Reformat a function signature to a more compact form.""" |
| 483 | + s = _cleanup_signature(sig) |
| 484 | + |
461 | 485 | # Strip return type annotation |
462 | | - s = re.sub(r"\)\s*->\s.*$", ")", sig) |
| 486 | + s = re.sub(r"\)\s*->\s.*$", ")", s) |
463 | 487 |
|
464 | 488 | # Remove parenthesis |
465 | 489 | s = re.sub(r"^\((.*)\)$", r"\1", s).strip() |
|
0 commit comments