docstring-inheritance


Namedocstring-inheritance JSON
Version 2.1.2 PyPI version JSON
download
home_page
SummaryAvoid writing and maintaining duplicated docstrings.
upload_time2023-12-17 07:38:14
maintainer
docs_urlNone
authorAntoine Dechaume
requires_python<3.13,>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            <!--
 Copyright 2021 Antoine DECHAUME

 This work is licensed under the Creative Commons Attribution 4.0
 International License. To view a copy of this license, visit
 http://creativecommons.org/licenses/by/4.0/ or send a letter to Creative
 Commons, PO Box 1866, Mountain View, CA 94042, USA.
 -->

![PyPI - Python Version](https://img.shields.io/pypi/pyversions/docstring-inheritance)
![PyPI](https://img.shields.io/pypi/v/docstring-inheritance)
![Conda (channel only)](https://img.shields.io/conda/vn/conda-forge/docstring-inheritance)
![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)
![Codecov branch](https://img.shields.io/codecov/c/gh/AntoineD/docstring-inheritance/main)

`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):
    - [NumPy docstring format specification](https://numpydoc.readthedocs.io/en/latest/format.html)
    - [Google docstring format specification](https://google.github.io/styleguide/pyguide.html#38-comments-and-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 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](http://www.sphinx-doc.org/).
- Missing docstring sections for signature arguments can be notified by warnings
  when the environment variable `DOCSTRING_INHERITANCE_WARNS` is set.
- Docstring sections can be compared to detect duplicated or similar contents that could be inherited.

# Licenses

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

# Installation

Install with pip:

```commandline
pip install docstring-inheritance
```

Or with conda:

```commandline
conda install -c conda-forge docstring-inheritance
```

# Basic Usage

## Inheriting docstrings for classes

`docstring-inheritance` provides
[metaclasses](https://docs.python.org/3/reference/datamodel.html#customizing-class-creation)
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
if `__init__` method is documented in its own docstring.
Otherwise, if `__init__` method is documented in the class docstring,
use the `NumpyDocstringInheritanceInitMeta` metaclass.

Use the `GoogleDocstringInheritanceMeta` metaclass to inherit docstrings in google format.
if `__init__` method is documented in its own docstring.
Otherwise, if `__init__` method is documented in the class docstring,
use the `GoogleDocstringInheritanceInitMeta` metaclass.

```python
from docstring_inheritance import NumpyDocstringInheritanceMeta


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

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

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


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

    Returns
    -------
    Something.

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


# The inherited docstring is
Child.method.__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.

```python
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](https://numpydoc.readthedocs.io/en/latest/format.html):
- `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](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)
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:

```python
from docstring_inheritance import NumpyDocstringInheritanceMeta


class Parent(metaclass=NumpyDocstringInheritanceMeta):
  """
  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 attribute `y` has been overridden
and the description for the attribute `z` has been added.
The only remaining description from the parent is for the attribute `x`.

### Sections documenting signatures

Those sections are:
- `Parameters` (numpy format only)
- `Args` (google format only)

In addition to the inheritance behavior described [above](#sections-with-items):
- the arguments not existing in the inheritor signature are removed,
- the arguments are sorted according the inheritor signature,
- the arguments with no description are provided with a dummy description.

```python
from docstring_inheritance import GoogleDocstringInheritanceMeta


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


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


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

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

# Advanced usage

## Abstract base class

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

```python
import abc
from docstring_inheritance import NumpyDocstringInheritanceMeta


class Meta(abc.ABCMeta, NumpyDocstringInheritanceMeta):
  pass


class Parent(metaclass=Meta):
  pass
```

## Detecting similar docstrings

Duplicated docstrings that could benefit from inheritance can be detected
by setting the environment variable `DOCSTRING_INHERITANCE_SIMILARITY_RATIO` to a value between `0` and `1`.
When set, the docstring sections of a child and its parent are compared and warnings are issued when the docstrings are
similar.
The docstring sections are compared with
[difflib ratio](https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.ratio)
from the standard library.
If the ratio is higher or equal to the value of `DOCSTRING_INHERITANCE_SIMILARITY_RATIO`,
the docstring sections are considered similar.
Use a ratio of `1` to detect identical docstring sections.
Use a ratio lower than `1` to detect similar docstring sections.

# Similar projects

[custom_inherit](https://github.com/rsokl/custom_inherit):
`docstring-inherit` started as fork of this project before being re-written,
we thank its author.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "docstring-inheritance",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "<3.13,>=3.8",
    "maintainer_email": "",
    "keywords": "",
    "author": "Antoine Dechaume",
    "author_email": "",
    "download_url": "",
    "platform": null,
    "description": "<!--\n Copyright 2021 Antoine DECHAUME\n\n This work is licensed under the Creative Commons Attribution 4.0\n International License. To view a copy of this license, visit\n http://creativecommons.org/licenses/by/4.0/ or send a letter to Creative\n Commons, PO Box 1866, Mountain View, CA 94042, USA.\n -->\n\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/docstring-inheritance)\n![PyPI](https://img.shields.io/pypi/v/docstring-inheritance)\n![Conda (channel only)](https://img.shields.io/conda/vn/conda-forge/docstring-inheritance)\n![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)\n![Codecov branch](https://img.shields.io/codecov/c/gh/AntoineD/docstring-inheritance/main)\n\n`docstring-inheritance` is a python package to avoid writing and maintaining duplicated python docstrings.\nThe typical usage is to enable the inheritance of the docstrings from a base class\nsuch that its derived classes fully or partly inherit the docstrings.\n\n# Features\n\n- Handle numpy and google docstring formats (i.e. sections based docstrings):\n    - [NumPy docstring format specification](https://numpydoc.readthedocs.io/en/latest/format.html)\n    - [Google docstring format specification](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n- Handle docstrings for functions, classes, methods, class methods, static methods, properties.\n- Handle docstrings for classes with multiple or multi-level inheritance.\n- Docstring sections are inherited individually,\n  like methods.\n- For docstring sections documenting signatures,\n  the signature arguments are inherited individually.\n- Minimum performance cost: the inheritance is performed at import time,\n  not for each call.\n- Compatible with rendering the documentation with [Sphinx](http://www.sphinx-doc.org/).\n- Missing docstring sections for signature arguments can be notified by warnings\n  when the environment variable `DOCSTRING_INHERITANCE_WARNS` is set.\n- Docstring sections can be compared to detect duplicated or similar contents that could be inherited.\n\n# Licenses\n\nThe source code is distributed under the MIT license.\nThe documentation is distributed under the CC BY 4.0 license.\nThe dependencies, with their licenses, are given in the CREDITS.md file.\n\n# Installation\n\nInstall with pip:\n\n```commandline\npip install docstring-inheritance\n```\n\nOr with conda:\n\n```commandline\nconda install -c conda-forge docstring-inheritance\n```\n\n# Basic Usage\n\n## Inheriting docstrings for classes\n\n`docstring-inheritance` provides\n[metaclasses](https://docs.python.org/3/reference/datamodel.html#customizing-class-creation)\nto enable the docstrings of a class to be inherited from its base classes.\nThis feature is automatically transmitted to its derived classes as well.\nThe docstring inheritance is performed for the docstrings of the:\n- class\n- methods\n- classmethods\n- staticmethods\n- properties\n\nUse the `NumpyDocstringInheritanceMeta` metaclass to inherit docstrings in numpy format\nif `__init__` method is documented in its own docstring.\nOtherwise, if `__init__` method is documented in the class docstring,\nuse the `NumpyDocstringInheritanceInitMeta` metaclass.\n\nUse the `GoogleDocstringInheritanceMeta` metaclass to inherit docstrings in google format.\nif `__init__` method is documented in its own docstring.\nOtherwise, if `__init__` method is documented in the class docstring,\nuse the `GoogleDocstringInheritanceInitMeta` metaclass.\n\n```python\nfrom docstring_inheritance import NumpyDocstringInheritanceMeta\n\n\nclass Parent(metaclass=NumpyDocstringInheritanceMeta):\n  def method(self, x, y=None):\n    \"\"\"Parent summary.\n\n    Parameters\n    ----------\n    x:\n       Description for x.\n    y:\n       Description for y.\n\n    Notes\n    -----\n    Parent notes.\n    \"\"\"\n\n\nclass Child(Parent):\n  def method(self, x, z):\n    \"\"\"\n    Parameters\n    ----------\n    z:\n       Description for z.\n\n    Returns\n    -------\n    Something.\n\n    Notes\n    -----\n    Child notes.\n    \"\"\"\n\n\n# The inherited docstring is\nChild.method.__doc__ == \"\"\"Parent summary.\n\nParameters\n----------\nx:\n   Description for x.\nz:\n   Description for z.\n\nReturns\n-------\nSomething.\n\nNotes\n-----\nChild notes.\n\"\"\"\n```\n\n## Inheriting docstrings for functions\n\n`docstring-inheritance` provides functions to inherit the docstring of a callable from a string.\nThis is typically used to inherit the docstring of a function from another function.\n\nUse the `inherit_google_docstring` function to inherit docstrings in google format.\n\nUse the `inherit_numpy_docstring` function to inherit docstrings in numpy format.\n\n```python\nfrom docstring_inheritance import inherit_google_docstring\n\n\ndef parent():\n    \"\"\"Parent summary.\n\n    Args:\n        x: Description for x.\n        y: Description for y.\n\n    Notes:\n        Parent notes.\n    \"\"\"\n\n\ndef child():\n    \"\"\"\n    Args:\n        z: Description for z.\n\n    Returns:\n        Something.\n\n    Notes:\n        Child notes.\n    \"\"\"\n\n\ninherit_google_docstring(parent.__doc__, child)\n\n# The inherited docstring is\nchild.__doc__ == \"\"\"Parent summary.\n\nArgs:\n    x: Description for x.\n    z: Description for z.\n\nReturns:\n    Something.\n\nNotes:\n    Child notes.\n\"\"\"\n```\n\n# Docstring inheritance specification\n\n## Sections order\n\nThe sections of an inherited docstring are sorted according to order defined in the\n[NumPy docstring format specification](https://numpydoc.readthedocs.io/en/latest/format.html):\n- `Summary`\n- `Extended summary`\n- `Parameters` for the NumPy format or `Args` for the Google format\n- `Returns`\n- `Yields`\n- `Receives`\n- `Other Parameters`\n- `Attributes`\n- `Methods`\n- `Raises`\n- `Warns`\n- `Warnings`\n- `See Also`\n- `Notes`\n- `References`\n- `Examples`\n- sections with other names come next\n\nThis ordering is also used for the docstring written with the\n[Google docstring format specification](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\neven though it does not define all of these sections.\n\n## Sections with items\n\nThose sections are:\n- `Other Parameters`\n- `Methods`\n- `Attributes`\n\nThe inheritance is done at the key level,\ni.e. a section of the inheritor will not fully override the parent one:\n- the keys in the parent section and not in the child section are inherited,\n- the keys in the child section and not in the parent section are kept,\n- for keys that are both in the parent and child section,\n  the child ones are kept.\n\nThis allows to only document the new keys in such a section of an inheritor.\nFor instance:\n\n```python\nfrom docstring_inheritance import NumpyDocstringInheritanceMeta\n\n\nclass Parent(metaclass=NumpyDocstringInheritanceMeta):\n  \"\"\"\n  Attributes\n  ----------\n  x:\n     Description for x\n  y:\n     Description for y\n  \"\"\"\n\n\nclass Child(Parent):\n  \"\"\"\n  Attributes\n  ----------\n  y:\n     Overridden description for y\n  z:\n     Description for z\n  \"\"\"\n\n\n# The inherited docstring is\nChild.__doc__ == \"\"\"\nAttributes\n----------\nx:\n   Description for x\ny:\n   Overridden description for y\nz:\n   Description for z\n\"\"\"\n```\n\nHere the keys are the attribute names.\nThe description for the attribute `y` has been overridden\nand the description for the attribute `z` has been added.\nThe only remaining description from the parent is for the attribute `x`.\n\n### Sections documenting signatures\n\nThose sections are:\n- `Parameters` (numpy format only)\n- `Args` (google format only)\n\nIn addition to the inheritance behavior described [above](#sections-with-items):\n- the arguments not existing in the inheritor signature are removed,\n- the arguments are sorted according the inheritor signature,\n- the arguments with no description are provided with a dummy description.\n\n```python\nfrom docstring_inheritance import GoogleDocstringInheritanceMeta\n\n\nclass Parent(metaclass=GoogleDocstringInheritanceMeta):\n  def method(self, w, x, y):\n    \"\"\"\n    Args:\n        w: Description for w\n        x: Description for x\n        y: Description for y\n    \"\"\"\n\n\nclass Child(Parent):\n  def method(self, w, y, z):\n    \"\"\"\n    Args:\n        z: Description for z\n        y: Overridden description for y\n    \"\"\"\n\n\n# The inherited docstring is\nChild.method.__doc__ == \"\"\"\nArgs:\n    w: Description for w\n    y: Overridden description for y\n    z: Description for z\n\"\"\"\n```\n\nHere the keys are the argument names.\nThe description for the argument `y` has been overridden\nand the description for the argument `z` has been added.\nThe only remaining description from the parent is for the argument `w`.\n\n# Advanced usage\n\n## Abstract base class\n\nTo create a parent class that both is abstract and has docstring inheritance,\nan additional metaclass is required:\n\n```python\nimport abc\nfrom docstring_inheritance import NumpyDocstringInheritanceMeta\n\n\nclass Meta(abc.ABCMeta, NumpyDocstringInheritanceMeta):\n  pass\n\n\nclass Parent(metaclass=Meta):\n  pass\n```\n\n## Detecting similar docstrings\n\nDuplicated docstrings that could benefit from inheritance can be detected\nby setting the environment variable `DOCSTRING_INHERITANCE_SIMILARITY_RATIO` to a value between `0` and `1`.\nWhen set, the docstring sections of a child and its parent are compared and warnings are issued when the docstrings are\nsimilar.\nThe docstring sections are compared with\n[difflib ratio](https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.ratio)\nfrom the standard library.\nIf the ratio is higher or equal to the value of `DOCSTRING_INHERITANCE_SIMILARITY_RATIO`,\nthe docstring sections are considered similar.\nUse a ratio of `1` to detect identical docstring sections.\nUse a ratio lower than `1` to detect similar docstring sections.\n\n# Similar projects\n\n[custom_inherit](https://github.com/rsokl/custom_inherit):\n`docstring-inherit` started as fork of this project before being re-written,\nwe thank its author.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Avoid writing and maintaining duplicated docstrings.",
    "version": "2.1.2",
    "project_urls": {
        "Documentation": "https://antoined.github.io/docstring-inheritance",
        "Homepage": "https://github.com/AntoineD/docstring-inheritance",
        "Source": "https://github.com/AntoineD/docstring-inheritance",
        "Tracker": "https://github.com/AntoineD/docstring-inheritance/issues"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d6c5fca4270777091c3b7275409fa7ba51768197da64dfe26cc9f5989c19403c",
                "md5": "7dce2e75fff056eac7edc9529203258c",
                "sha256": "05c8e3ef4c308406e66345b6d583df48ec1803ae90ae39cb7be03a78ac8d88d1"
            },
            "downloads": -1,
            "filename": "docstring_inheritance-2.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "7dce2e75fff056eac7edc9529203258c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<3.13,>=3.8",
            "size": 21900,
            "upload_time": "2023-12-17T07:38:14",
            "upload_time_iso_8601": "2023-12-17T07:38:14.788989Z",
            "url": "https://files.pythonhosted.org/packages/d6/c5/fca4270777091c3b7275409fa7ba51768197da64dfe26cc9f5989c19403c/docstring_inheritance-2.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-17 07:38:14",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "AntoineD",
    "github_project": "docstring-inheritance",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "tox": true,
    "lcname": "docstring-inheritance"
}
        
Elapsed time: 0.18470s