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.

Sphinx Bootstrap Theme

Sphinx Bootstrap Theme This Sphinx theme integrates the Bootstrap CSS / JavaScript framework with various layout options, hierarchical menu navigation

Ryan Roemer 584 Nov 16, 2022
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
This is a template (starter kit) for writing Maturity Work with Sphinx / LaTeX at Collège du Sud

sphinx-tm-template Ce dépôt est un template de base utilisable pour écrire ton travail de maturité dans le séminaire d'informatique du Collège du Sud.

6 Dec 22, 2022
A comprehensive and FREE Online Python Development tutorial going step-by-step into the world of Python.

FREE Reverse Engineering Self-Study Course HERE Fundamental Python The book and code repo for the FREE Fundamental Python book by Kevin Thomas. FREE B

Kevin Thomas 7 Mar 19, 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
Pystm32ai - A Python wrapper for the stm32ai command-line tool

PySTM32.AI A python wrapper for the stm32ai command-line tool to analyse deep le

Thibaut Vercueil 5 Jul 28, 2022
🌱 Complete API wrapper of Seedr.cc

Python API Wrapper of Seedr.cc Table of Contents Installation How I got the API endpoints? Start Guide Getting Token Logging with Username and Passwor

Hemanta Pokharel 43 Dec 26, 2022
Portfolio project for Code Institute Full Stack software development course.

Comic Sales tracker This project is the third milestone project for the Code Institute Diploma in Full Stack Software Development. You can see the fin

1 Jan 10, 2022
Python-samples - This project is to help someone need some practices when learning python language

Python-samples - This project is to help someone need some practices when learning python language

Gui Chen 0 Feb 14, 2022
Poetry plugin to export the dependencies to various formats

Poetry export plugin This package is a plugin that allows the export of locked packages to various formats. Note: For now, only the requirements.txt f

Poetry 90 Jan 05, 2023
An open source utility for creating publication quality LaTex figures generated from OpenFOAM data files.

foamTEX An open source utility for creating publication quality LaTex figures generated from OpenFOAM data files. Explore the docs » Report Bug · Requ

1 Dec 19, 2021
YAML metadata extension for Python-Markdown

YAML metadata extension for Python-Markdown This extension adds YAML meta data handling to markdown with all YAML features. As in the original, metada

Nikita Sivakov 14 Dec 30, 2022
Near Zero-Overhead Python Code Coverage

Slipcover: Near Zero-Overhead Python Code Coverage by Juan Altmayer Pizzorno and Emery Berger at UMass Amherst's PLASMA lab. About Slipcover Slipcover

PLASMA @ UMass 325 Dec 28, 2022
Collection of Summer 2022 tech internships!

Collection of Summer 2022 tech internships!

Pitt Computer Science Club (CSC) 15.6k Jan 03, 2023
Yu-Gi-Oh! Master Duel translation script

Yu-Gi-Oh! Master Duel translation script

715 Jan 08, 2023
Contains the assignments from the course Building a Modern Computer from First Principles: From Nand to Tetris.

Contains the assignments from the course Building a Modern Computer from First Principles: From Nand to Tetris.

Matheus Rodrigues 1 Jan 20, 2022
Explain yourself! Interrogate a codebase for docstring coverage.

interrogate: explain yourself Interrogate a codebase for docstring coverage. Why Do I Need This? interrogate checks your code base for missing docstri

Lynn Root 435 Dec 29, 2022
DeltaPy - Tabular Data Augmentation (by @firmai)

DeltaPy⁠⁠ — Tabular Data Augmentation & Feature Engineering Finance Quant Machine Learning ML-Quant.com - Automated Research Repository Introduction T

Derek Snow 470 Dec 28, 2022
Quick tutorial on orchest.io that shows how to build multiple deep learning models on your data with a single line of code using python

Deep AutoViML Pipeline for orchest.io Quickstart Build Deep Learning models with a single line of code: deep_autoviml Deep AutoViML helps you build te

Ram Seshadri 6 Oct 02, 2022
The OpenAPI Specification Repository

The OpenAPI Specification The OpenAPI Specification is a community-driven open specification within the OpenAPI Initiative, a Linux Foundation Collabo

OpenAPI Initiative 25.5k Dec 29, 2022