pythonpython-sphinxdocstringautodoc

Sphinx Autodoc: display the choices of a param from a variable


I have some parameters that accept only a set of values and these authorized values are stored into a list. Is it possible to use the content of this list in the docstring?

For example:

authorized_values = [1, 2, 3]

def foo(a: int):
    """Print an integer between 1 and 3.

    Args:
        a: The integer to print. The authorized values are: <authorized_values>.
    """
    if a not in authorized_value:
        raise ValueError(f"The authorized values are: {authorized_values}.")
    print(a)

This would ensure the docs is synchronized with the code. Because if I want to add a new authorized value, I have to update the code and the docstrings to ensure they are in sync, which I would like to avoid.


Solution

  • You could use a decorator to modify the docstring. Something like

    authorized_values = [1, 2, 3]
    
    
    def doc_format(func):
        func.__doc__ = func.__doc__.replace("AUTHORIZED_VALUES", str(authorized_values))
        return func
    
    
    @doc_format
    def foo(a: int):
        """Print an integer between 1 and 3.
    
        Args:
            a: The integer to print. The authorized values are: AUTHORIZED_VALUES.
        """
    
    
    help(foo)