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.

Fully reproducible, Dockerized, step-by-step, tutorial on how to mock a "real-time" Kafka data stream from a timestamped csv file. Detailed blog post published on Towards Data Science.

time-series-kafka-demo Mock stream producer for time series data using Kafka. I walk through this tutorial and others here on GitHub and on my Medium

Maria Patterson 26 Nov 15, 2022
Python-slp - Side Ledger Protocol With Python

Side Ledger Protocol Run python-slp node First install Mongo DB and run the mong

Solar 3 Mar 02, 2022
Grokking the Object Oriented Design Interview

Grokking the Object Oriented Design Interview

Tusamma Sal Sabil 2.6k Jan 08, 2023
Some code that takes a pipe-separated input and converts that into a table!

tablemaker A program that takes an input: a | b | c # With comments as well. e | f | g h | i |jk And converts it to a table: ┌───┬───┬────┐ │ a │ b │

CodingSoda 2 Aug 30, 2022
A Python Package To Generate Strong Passwords For You in Your Projects.

shPassGenerator Version 1.0.6 Ready To Use Developed by Shervin Badanara (shervinbdndev) on Github Language and technologies used in This Project Work

Shervin 11 Dec 19, 2022
A next-generation curated knowledge sharing platform for data scientists and other technical professions.

Knowledge Repo The Knowledge Repo project is focused on facilitating the sharing of knowledge between data scientists and other technical roles using

Airbnb 5.2k Dec 27, 2022
CoderByte | Practice, Tutorials & Interview Preparation Solutions|

CoderByte | Practice, Tutorials & Interview Preparation Solutions This repository consists of solutions to CoderByte practice, tutorials, and intervie

Eda AYDIN 6 Aug 09, 2022
Cleaner script to normalize knock's output EPUBs

clean-epub The excellent knock application by Benton Edmondson outputs EPUBs that seem to be DRM-free. However, if you run the application twice on th

2 Dec 16, 2022
In this Github repository I will share my freqtrade files with you. I want to help people with this repository who don't know Freqtrade so much yet.

My Freqtrade stuff In this Github repository I will share my freqtrade files with you. I want to help people with this repository who don't know Freqt

Simon Kebekus 104 Dec 31, 2022
This programm checks your knowlege about the capital of Japan

Introduction This programm checks your knowlege about the capital of Japan. Now, what does it actually do? After you run the programm you get asked wh

1 Dec 16, 2021
Generating a report CSV and send it to an email - Python / Django Rest Framework

Generating a report in CSV format and sending it to a email How to start project. Create a folder in your machine Create a virtual environment python3

alexandre Lopes 1 Jan 17, 2022
VSCode extension that generates docstrings for python files

VSCode Python Docstring Generator Visual Studio Code extension to quickly generate docstrings for python functions. Features Quickly generate a docstr

Nils Werner 506 Jan 03, 2023
PySpark Cheat Sheet - learn PySpark and develop apps faster

This cheat sheet will help you learn PySpark and write PySpark apps faster. Everything in here is fully functional PySpark code you can run or adapt to your programs.

Carter Shanklin 168 Jan 01, 2023
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
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
204-python-string-21BCA90 created by GitHub Classroom

204-Python This repository is created for subject "204 Programming Skill" Python Programming. This Repository contain list of programs of python progr

VIDYABHARTI TRUST COLLEGE OF BCA 6 Mar 31, 2022
Python code for working with NFL play by play data.

nfl_data_py nfl_data_py is a Python library for interacting with NFL data sourced from nflfastR, nfldata, dynastyprocess, and Draft Scout. Includes im

82 Jan 05, 2023
A Python module for creating Excel XLSX files.

XlsxWriter XlsxWriter is a Python module for writing files in the Excel 2007+ XLSX file format. XlsxWriter can be used to write text, numbers, formula

John McNamara 3.1k Dec 29, 2022
💻An open-source eBook with 101 Linux commands that everyone should know

This is an open-source eBook with 101 Linux commands that everyone should know. No matter if you are a DevOps/SysOps engineer, developer, or just a Linux enthusiast, you will most likely have to use

Ashfaque Ahmed 0 Oct 29, 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