numpydoc icon indicating copy to clipboard operation
numpydoc copied to clipboard

FR: Add "Supported Signatures" Section to the NumPy Docstring Style Guide

Open adam-grant-hendry opened this issue 3 years ago • 1 comments

Python doesn't natively support function overloading (like how C++ does), but imitates it with optional positional and keyword arguments. With the advent of the typing.overload decorator, we have the ability to express correlations between parameter and return types. C/C++ and Fortran methods ported to Python sometimes have function overloads that differ in arity and type. For polymorphic functions, it would be nice to have a section in the docstring describing the accepted signatures for a function.

A suggestion (dummy example) of what this might look like is:

from __future__ import annotations

from collections.abc import Sequence


def double(input_: int | Sequence[int]) -> int | list[int]:
    """Returns the input doubled.

    If the input is a sequence, returns the sequence
    with every item doubled. Otherwise, it returns
    the passed number doubled.

    Parameters
    ----------
    input_ : int or Sequence[int]
        The number (or number array) to be doubled

    Supported Signatures
    --------------------
    double( int ) -> int
    double( Sequence[int] ) -> list[int]

    Returns
    -------
    int or list[int]
        The input doubled if the input is a single ``int``,
        else the list with its elements doubled.
    """
    ...

adam-grant-hendry avatar Sep 19 '22 02:09 adam-grant-hendry

Thanks for the suggestion @adam-grant-hendry. It makes sense to me to allow expression this information somehow. However, I'm hesitant for two reasons:

  1. We should be a bit careful not to encourage writing polymorphic functions where output types have to be deduced from input types rather than input values (including bool inputs, all the return_xxx= keywords in NumPy & beyond were not a great idea). So if we add this, it should come with some warning/disclaimer.
  2. Sphinx can use type annotations (see the autodoc docs), but AFAIK doesn't support overloads yet. A longer term solution should make sure to be compatible with what Sphinx may do.

And a question: how would you express functions where the output type matches the input type under Supported Signatures?

rgommers avatar Sep 19 '22 08:09 rgommers