sphinx icon indicating copy to clipboard operation
sphinx copied to clipboard

Autodoc type aliases in overloads

Open barakatzir opened this issue 10 months ago • 3 comments

Purpose

I noticed that in the autodoc extension, the autodoc_type_aliases was not respected in overload signatures. Even worse, it ruined type signature for import aliases (import ... as ...) in some cases.

I couldn't find an open issue for this so I'll describe it shortly here (maybe I missed?):

For example, if I want to document

from typing import overload
import numpy.typing as npt
import numpy as np
from collections.abc import Mapping

MyMap = Mapping[int, int]

@overload
def apply_map(x: tuple[npt.NDArray[np.int64], MyMap]) -> npt.NDArray[np.int64]: ...

@overload
def apply_map(x: tuple[list[int], MyMap]) -> list[int]: ...

def apply_map(x): ...

Then setting autodoc_type_aliases = {'MyMap': 'mapster.MyMap'} (just about any non-trivial mapping) will not be applied, and the np and npt aliases will not be resolved correctly and left as np and npt.

I looked in the source code, and saw that the signature for overloads is obtained differently from non-overloaded callables. Usually callables use typing.get_type_hints under the hood while overloads use an AST variant of signature determination. I switched the overloads to use FunctionDocumenter and MethodDocumenter to obtain the signatures using typing.get_overloads which returns the overloads as callables (a python>=3.11 feature).

Since the Documenters are used to resolve the signatures this solves issue https://github.com/sphinx-doc/sphinx/issues/10351. This customization can probably allow for a workaround for https://github.com/sphinx-doc/sphinx/issues/10359. This also partially solves https://github.com/sphinx-doc/sphinx/issues/9813.

I tried briefly to fix also so autodoc_type_aliases works on attributes and module members and got stuck in a wall so I left it as is.

References

barakatzir avatar Feb 13 '25 19:02 barakatzir

It wasn't clear to me at first that the number in the CHANGES.rst reference the relevant issues (🤦🏼‍♂️). Fixed now.

barakatzir avatar Feb 13 '25 22:02 barakatzir

I chose to switch the overload signature handling from using sphinx.util.inspect.signature_from_ast function to use the usual Documenter one (via sphinx.util.inspect.signature which uses typing.get_type_hints). If you think that it's better to use the AST variant (for example if for some reason it can handle the TYPE_CHECKING blocks better), I'm willing to try to fix the AST behavior so that it works with type aliasing.

barakatzir avatar Feb 14 '25 14:02 barakatzir

@AA-Turner, did you get a chance to look at my PR? If not, I can wait.

If it is not on par with the code standards I'm willing to fix it. If the subject I'm raising is a non-issue I can simply close the PR without opening an issue.

barakatzir avatar Feb 18 '25 07:02 barakatzir