Skip to content

Commit 8f45bee

Browse files
authored
Merge pull request #7291 from anntzer/signature-rewritten-singledispatch
Handle singledispatch functions with rewritten signatures.
2 parents 5caaa55 + f9048cf commit 8f45bee

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

sphinx/ext/autodoc/__init__.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import importlib
1414
import re
1515
import warnings
16+
from inspect import Parameter
1617
from types import ModuleType
1718
from typing import Any, Callable, Dict, Iterator, List, Sequence, Set, Tuple, Type, Union
1819
from unittest.mock import patch
@@ -1108,9 +1109,10 @@ def annotate_to_first_argument(self, func: Callable, typ: Type) -> None:
11081109
if len(sig.parameters) == 0:
11091110
return
11101111

1111-
name = list(sig.parameters)[0]
1112-
if name not in func.__annotations__:
1113-
func.__annotations__[name] = typ
1112+
params = list(sig.parameters.values())
1113+
if params[0].annotation is Parameter.empty:
1114+
params[0] = params[0].replace(annotation=typ)
1115+
func.__signature__ = sig.replace(parameters=params) # type: ignore
11141116

11151117

11161118
class DecoratorDocumenter(FunctionDocumenter):
@@ -1508,13 +1510,14 @@ def add_directive_header(self, sig: str) -> None:
15081510

15091511
def annotate_to_first_argument(self, func: Callable, typ: Type) -> None:
15101512
"""Annotate type hint to the first argument of function if needed."""
1511-
sig = inspect.signature(func, bound_method=True)
1512-
if len(sig.parameters) == 0:
1513+
sig = inspect.signature(func)
1514+
if len(sig.parameters) == 1:
15131515
return
15141516

1515-
name = list(sig.parameters)[0]
1516-
if name not in func.__annotations__:
1517-
func.__annotations__[name] = typ
1517+
params = list(sig.parameters.values())
1518+
if params[1].annotation is Parameter.empty:
1519+
params[1] = params[1].replace(annotation=typ)
1520+
func.__signature__ = sig.replace(parameters=params) # type: ignore
15181521

15191522

15201523
class AttributeDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter): # type: ignore

tests/roots/test-ext-autodoc/target/singledispatch.py

+8
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
11
from functools import singledispatch
2+
import inspect
3+
4+
5+
def assign_signature(func):
6+
# This is intended to cover more complex signature-rewriting decorators.
7+
func.__signature__ = inspect.signature(func)
8+
return func
29

310

411
@singledispatch
@@ -14,6 +21,7 @@ def _func_int(arg, kwarg=None):
1421

1522

1623
@func.register(str)
24+
@assign_signature
1725
def _func_str(arg, kwarg=None):
1826
"""A function for str."""
1927
pass

0 commit comments

Comments
 (0)