docstring-inheritance icon indicating copy to clipboard operation
docstring-inheritance copied to clipboard

Decorator to inherit docstring

Open haiiliin opened this issue 2 years ago • 0 comments

Using a decorator to inherit the docstring would be very useful. For example, the decorator's definition would be like this:

from typing import Callable, Literal

def inherit_docstring(func: Callable = None, *, source: Callable = None, style: Literal["numpy", "google"] = "numpy"):
    """Decorator for inherit docstring from other functions."""
    from docstring_inheritance import inherit_google_docstring, inherit_numpy_docstring

    assert source is not None, "Source function is not given."
    assert style in ("numpy", "google"), "Style must be either 'numpy' or 'google'."

    def wrapper(f):
        inherit_func = inherit_numpy_docstring if style == "numpy" else inherit_google_docstring
        inherit_func(source.__doc__, f)
        return f

    return wrapper if func is None else wrapper(func)

With the following usage:

def parent(x, y):
  """Parent summary.

  Args:
      x: Description for x.
      y: Description for y.

  Notes:
      Parent notes.
  """

@inherit_docstring(source=parent, style="google")
def child(x, y, z):
  """
  Args:
      z: Description for z.

  Returns:
      Something.

  Notes:
      Child notes.
  """

The child's docstring is:

>>> print(child.__doc__)
Parent summary.

Args:
    x: Description for x.
    y: Description for y.
    z: Description for z.

Returns:
    Something.

Notes:
    Child notes.

haiiliin avatar Oct 27 '23 03:10 haiiliin