Skip to content

Decorator to inherit docstring #9

Closed
@haiiliin

Description

@haiiliin

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions