Search code examples
pythonpython-sphinxtype-hintingtype-alias

Keeping alias types simple in Python documentation?


I'm trying to use the typing module to document my Python package, and I have a number of situations where several different types are allowable for a function parameter. For instance, you can either pass a number, an Envelope object (one of the classes in my package), or a list of numbers from which an Envelope is constructed, or a list of lists of numbers from which an envelope is constructed. So I make an alias type as follows:

NumberOrEnvelope = Union[Sequence[Real], Sequence[Sequence[Real]], Real, Envelope]

Then I write the function:

def example_function(parameter: NumberOrEnvelope):
    ...

And that looks great to me. However, when I create the documentation using Sphinx, I end up with this horrifically unreadable function signature:

example_function(parameter: Union[Sequence[numbers.Real], Sequence[Sequence[numbers.Real]], numbers.Real, expenvelope.envelope.Envelope])

Same thing also with the hints that pop up when I start to try to use the function in PyCharm.

Is there some way I can have it just leave it as "NumberOrEnvelope". Ideally that would also link in the documentation to a clarification of what "NumberOrEnvelope" is, though even if it didn't it would be way better than what's appearing now.


Solution

  • I had the same issue and used https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_type_aliases, introduced in version 3.3.

    In your sphinx conf.py, insert this section. It does not seem to make much sense at the first sight, but does the trick:

    autodoc_type_aliases = dict(NumberOrEnvelope='NumberOrEnvelope')
    

    Warning: It only works in modules that start with from __future__ import annotation

    Note: If there is a target in the documentation, type references even have a hyperlink to the definition. I have classes, documented elsewhere with autoclass, which are used as types of function parameters, and the docs show the nice names of the types with links.