A python package to avoid writing and maintaining duplicated python docstrings.

Overview

PyPI - Python Version PyPI Code Style Codecov branch

docstring-inheritance is a python package to avoid writing and maintaining duplicated python docstrings. The typical usage is to enable the inheritance of the docstrings from a base class such that its derived classes fully or partly inherit the docstrings.

Features

  • Handle numpy and google docstring formats (i.e. sections based docstrings):
  • Handle docstrings for functions, classes, methods, class methods, static methods, properties.
  • Handle docstrings for classes with multiple or multi-level inheritance.
  • Docstring sections are inherited individually, like methods for a classes.
  • For docstring sections documenting signatures, the signature arguments are inherited individually.
  • Minimum performance cost: the inheritance is performed at import time, not for each call.
  • Compatible with rendering the documentation with Sphinx.

Licenses

The source code is distributed under the MIT license. The documentation is distributed under the CC BY-SA 4.0 license. The dependencies, with their licenses, are given in the CREDITS.rst file.

Installation

Install via pip:

pip install docstring-inheritance

Basic Usage

Inheriting docstrings for classes

docstring-inheritance provides metaclasses to enable the docstrings of a class to be inherited from its base classes. This feature is automatically transmitted to its derived classes as well. The docstring inheritance is performed for the docstrings of the:

  • class
  • methods
  • classmethods
  • staticmethods
  • properties

Use the NumpyDocstringInheritanceMeta metaclass to inherit docstrings in numpy format.

Use the GoogleDocstringInheritanceMeta metaclass to inherit docstrings in google format.

from docstring_inheritance import NumpyDocstringInheritorMeta


class Parent(metaclass=NumpyDocstringInheritorMeta):
    def meth(self, x, y=None):
        """Parent summary.

        Parameters
        ----------
        x:
           Description for x.
        y:
           Description for y.

        Notes
        -----
        Parent notes.
        """


class Child(Parent):
    def meth(self, x, z):
        """
        Parameters
        ----------
        z:
           Description for z.

        Returns
        -------
        Something.

        Notes
        -----
        Child notes.
        """


# The inherited docstring is
Child.meth.__doc__ = """Parent summary.

Parameters
----------
x:
   Description for x.
z:
   Description for z.

Returns
-------
Something.

Notes
-----
Child notes.
"""

Inheriting docstrings for functions

docstring-inheritance provides functions to inherit the docstring of a callable from a string. This is typically used to inherit the docstring of a function from another function.

Use the inherit_google_docstring function to inherit docstrings in google format.

Use the inherit_numpy_docstring function to inherit docstrings in numpy format.

from docstring_inheritance import inherit_google_docstring


def parent():
    """Parent summary.

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

    Notes:
        Parent notes.
    """


def child():
    """
    Args:
        z: Description for z.

    Returns:
        Something.

    Notes:
        Child notes.
    """
    

inherit_google_docstring(parent.__doc__, child)


# The inherited docstring is
child.__doc__ = """Parent summary.

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

Returns:
    Something.

Notes:
    Child notes.
"""

Docstring inheritance specification

Sections order

The sections of an inherited docstring are sorted according to order defined in the NumPy docstring format specification:

  • Summary
  • Extended summary
  • Parameters for the NumPy format or Args for the Google format
  • Returns
  • Yields
  • Receives
  • Other Parameters
  • Attributes
  • Methods
  • Raises
  • Warns
  • Warnings
  • See Also
  • Notes
  • References
  • Examples
  • sections with other names come next

This ordering is also used for the docstring written with the Google docstring format specification even though it does not define all of these sections.

Sections with items

Those sections are:

  • Other Parameters
  • Methods
  • Attributes

The inheritance is done at the key level, i.e. a section of the inheritor will not fully override the parent one:

  • the keys in the parent section and not in the child section are inherited,
  • the keys in the child section and not in the parent section are kept,
  • for keys that are both in the parent and child section, the child ones are kept.

This allows to only document the new keys in such a section of an inheritor. For instance:

from docstring_inheritance import NumpyDocstringInheritorMeta


class Parent(metaclass=NumpyDocstringInheritorMeta):
    """
    Attributes
    ----------
    x:
       Description for x
    y:
       Description for y
    """


class Child(Parent):
    """
    Attributes
    ----------
    y:
       Overridden description for y
    z:
       Description for z
    """

    
# The inherited docstring is
Child.__doc__ = """
Attributes
----------
x:
   Description for x
y:
   Overridden description for y
z:
   Description for z
"""

Here the keys are the attribute names. The description for the key y has been overridden and the description for the key z has been added. The only remaining description from the parent is for the key x.

Sections documenting signatures

Those sections are:

  • Parameters (numpy format only)
  • Args (google format only)

In addition to the inheritance behavior described above:

  • the arguments not existing in the inheritor signature are removed,
  • the arguments are sorted according the inheritor signature,
  • the arguments with no descriptions are provided with a dummy description.
from docstring_inheritance import GoogleDocstringInheritorMeta


class Parent(metaclass=GoogleDocstringInheritorMeta):
    def meth(self, w, x, y):
        """
        Args:
            w: Description for w
            x: Description for x
            y: Description for y
        """


class Child(Parent):
    def meth(self, w, y, z):
        """
        Args:
            z: Description for z
            y: Overridden description for y
        """


# The inherited docstring is
Child.meth.__doc__ = """
Args:
    w: Description for w
    y: Overridden description for y
    z: Description for z
"""

Here the keys are the arguments names. The description for the key y has been overridden and the description for the key z has been added. The only remaining description from the parent is for the key w.

Advanced usage

Abstract base class

To create a parent class that both is abstract and has docstring inheritance, an additional metaclass is required:

import abc
from docstring_inheritance import NumpyDocstringInheritorMeta


class Meta(abc.ABCMeta, NumpyDocstringInheritorMeta):
    pass


class Parent(metaclass=Meta):
    pass

Similar projects

custom_inherit: docstring-inherit started as fork of this project, we would like to thank its author.

Speed up Sphinx builds by selectively removing toctrees from some pages

Remove toctrees from Sphinx pages Improve your Sphinx build time by selectively removing TocTree objects from pages. This is useful if your documentat

Executable Books 8 Jan 04, 2023
Mozilla Campus Club CCEW is a student committee working to spread awareness on Open Source software.

Mozilla Campus Club CCEW is a student committee working to spread awareness on Open Source software. We organize webinars and workshops on different technical topics and making Open Source contributi

Mozilla-Campus-Club-Cummins 8 Jun 15, 2022
Python solutions to solve practical business problems.

Python Business Analytics Also instead of "watching" you can join the link-letter, it's already being sent out to about 90 people and you are free to

Derek Snow 357 Dec 26, 2022
Your Project with Great Documentation.

Read Latest Documentation - Browse GitHub Code Repository The only thing worse than documentation never written, is documentation written but never di

Timothy Edmund Crosley 809 Dec 28, 2022
DataAnalysis: Some data analysis projects in charles_pikachu

DataAnalysis DataAnalysis: Some data analysis projects in charles_pikachu You can star this repository to keep track of the project if it's helpful fo

9 Nov 04, 2022
Fast syllable estimation library based on pattern matching.

Syllables: A fast syllable estimator for Python Syllables is a fast, simple syllable estimator for Python. It's intended for use in places where speed

ProseGrinder 26 Dec 14, 2022
A curated list of awesome mathematics resources

A curated list of awesome mathematics resources

Cyrille Rossant 6.7k Jan 05, 2023
learn python in 100 days, a simple step could be follow from beginner to master of every aspect of python programming and project also include side project which you can use as demo project for your personal portfolio

learn python in 100 days, a simple step could be follow from beginner to master of every aspect of python programming and project also include side project which you can use as demo project for your

BDFD 6 Nov 05, 2022
API spec validator and OpenAPI document generator for Python web frameworks.

API spec validator and OpenAPI document generator for Python web frameworks.

1001001 249 Dec 22, 2022
The project that powers MDN.

Kuma Kuma is the platform that powers MDN (developer.mozilla.org) Development Code: https://github.com/mdn/kuma Issues: P1 Bugs (to be fixed ASAP) P2

MDN Web Docs 1.9k Dec 26, 2022
Version bêta d'un système pour suivre les prix des livres chez Books to Scrape,

Version bêta d'un système pour suivre les prix des livres chez Books to Scrape, un revendeur de livres en ligne. En pratique, dans cette version bêta, le programme n'effectuera pas une véritable surv

Mouhamed Dia 1 Jan 06, 2022
An MkDocs plugin to export content pages as PDF files

MkDocs PDF Export Plugin An MkDocs plugin to export content pages as PDF files The pdf-export plugin will export all markdown pages in your MkDocs rep

Terry Zhao 266 Dec 13, 2022
The blazing-fast Discord bot.

Wavy Wavy is an open-source multipurpose Discord bot built with pycord. Wavy is still in development, so use it at your own risk. Tools and services u

Wavy 7 Dec 27, 2022
JTEX is a command line tool (CLI) for rendering LaTeX documents from jinja-style templates.

JTEX JTEX is a command line tool (CLI) for rendering LaTeX documents from jinja-style templates. This package uses Jinja2 as the template engine with

Curvenote 15 Dec 21, 2022
Hasköy is an open-source variable sans-serif typeface family

Hasköy Hasköy is an open-source variable sans-serif typeface family. Designed with powerful opentype features and each weight includes latin-extended

67 Jan 04, 2023
Workbench to integrate pyoptools with freecad, that means basically optics ray tracing capabilities for FreeCAD.

freecad-pyoptools Workbench to integrate pyoptools with freecad, that means basically optics ray tracing capabilities for FreeCAD. Requirements It req

Combustión Ingenieros SAS 12 Nov 16, 2022
NoVmpy - NoVmpy with python

git clone -b dev-1 https://github.com/wallds/VTIL-Python.git cd VTIL-Python py s

263 Dec 23, 2022
Comprehensive Python Cheatsheet

Comprehensive Python Cheatsheet Download text file, Buy PDF, Fork me on GitHub or Check out FAQ. Contents 1. Collections: List, Dictionary, Set, Tuple

Jefferson 1 Jan 23, 2022
Watch a Sphinx directory and rebuild the documentation when a change is detected. Also includes a livereload enabled web server.

sphinx-autobuild Rebuild Sphinx documentation on changes, with live-reload in the browser. Installation sphinx-autobuild is available on PyPI. It can

Executable Books 440 Jan 06, 2023
Mayan EDMS is a document management system.

Mayan EDMS is a document management system. Its main purpose is to store, introspect, and categorize files, with a strong emphasis on preserving the contextual and business information of documents.

3 Oct 02, 2021