numpydoc-decorator


Namenumpydoc-decorator JSON
Version 2.1.0 PyPI version JSON
download
home_page
Summary
upload_time2023-05-25 21:42:13
maintainer
docs_urlNone
authorAlistair Miles
requires_python>=3.8,<3.12
license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # numpydoc_decorator

This package allows you to build [numpy-style
docstrings](https://numpydoc.readthedocs.io/en/latest/format.html#sections)
programmatically and apply them using a decorator. This can be useful
because:

-   Parts of your documentation, such as parameter descriptions, can be
    shared between functions, avoiding the need to repeat yourself.

-   Type information for parameters and return values is automatically
    picked up from type annotations and added to the docstring, avoiding
    the need to maintain type information in two places.

## Installation

`pip install numpydoc_decorator`

## Usage

### Documentation a function

Here is an example of documenting a function:

```python
from numpydoc_decorator import doc


@doc(
    summary="Say hello to someone.",
    extended_summary="""
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
        minim veniam, quis nostrud exercitation ullamco laboris nisi ut
        aliquip ex ea commodo consequat. Duis aute irure dolor in
        reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
        culpa qui officia deserunt mollit anim id est laborum.
    """,
    parameters=dict(
        name="The name of the person to greet.",
        language="The language in which to greet as an ISO 639-1 code.",
    ),
    returns="A pleasant greeting.",
    raises=dict(
        NotImplementedError="If the requested language has not been implemented yet.",
        ValueError="If the language is not a valid ISO 639-1 code."
    ),
    see_also=dict(
        print="You could use this function to print your greeting.",
    ),
    notes="""
        This function is useful when greeting someone else. If you would
        like something to talk about next, you could try [1]_.
    """,
    references={
        "1": """
            O. McNoleg, "The integration of GIS, remote sensing, expert systems
            and adaptive co-kriging for environmental habitat modelling of the
            Highland Haggis using object-oriented, fuzzy-logic and neural-
            network techniques," Computers & Geosciences, vol. 22, pp. 585-588,
            1996.
        """,
    },
    examples="""
        Here is how to greet a friend in English:

        >>> print(greet("Ford Prefect"))
        Hello Ford Prefect!

        Here is how to greet someone in another language:

        >>> print(greet("Tricia MacMillan", language="fr"))
        Salut Tricia MacMillan!

    """,
)
def greet(
    name: str,
    language: str = "en",
) -> str:
    if len(language) != 2:
        raise ValueError("language must be an ISO 639-1 code")
    if language == "en":
        return f"Hello {name}!"
    elif language == "fr":
        return f"Salut {name}!"
    else:
        raise NotImplementedError(f"language {language} not implemented")
```

Here is the docstring that will be created and attached to the
decorated function:

```
>>> print(greet.__doc__)

Say hello to someone.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.

Parameters
----------
name : str
    The name of the person to greet.
language : str, optional, default: 'en'
    The language in which to greet as an ISO 639-1 code.

Returns
-------
str
    A pleasant greeting.

Raises
------
NotImplementedError
    If the requested language has not been implemented yet.
ValueError
    If the language is not a valid ISO 639-1 code.

See Also
--------
print : You could use this function to print your greeting.

Notes
-----
This function is useful when greeting someone else. If you would like
something to talk about next, you could try [1]_.

References
----------
.. [1] O. McNoleg, "The integration of GIS, remote sensing, expert systems
    and adaptive co-kriging for environmental habitat modelling of the
    Highland Haggis using object-oriented, fuzzy-logic and neural- network
    techniques," Computers & Geosciences, vol. 22, pp. 585-588, 1996.

Examples
--------
Here is how to greet a friend in English:

>>> print(greet("Ford Prefect"))
Hello Ford Prefect!

Here is how to greet someone in another language:

>>> print(greet("Tricia MacMillan", language="fr"))
Salut Tricia MacMillan!

```

### Shared parameters

If you have parameters which are common to multiple functions, here
is an approach you can take:

```python
from numpydoc_decorator import doc
from typing_extensions import Annotated


class params:
    name = Annotated[str, "The name of a person."]
    language = Annotated[str, "An ISO 639-1 language code."]


@doc(
    summary="Say hello to someone you know.",
    returns="A personal greeting.",
)
def say_hello(
    name: params.name,
    language: params.language,
) -> str:
    pass


@doc(
    summary="Say goodbye to someone you know.",
    returns="A personal parting.",
)
def say_goodbye(
    name: params.name,
    language: params.language,
) -> str:
    pass
```

Here are the generated docstrings:

```
>>> print(say_hello.__doc__)

Say hello to someone you know.

Parameters
----------
name : str
    The name of a person.
language : str
    An ISO 639-1 language code.

Returns
-------
str
    A personal greeting.
```

```
>>> print(say_goodbye.__doc__)

Say goodbye to someone you know.

Parameters
----------
name : str
    The name of a person.
language : str
    An ISO 639-1 language code.

Returns
-------
str
    A personal parting.
```

## Notes

There are probably lots of edge cases that this package has not
covered yet. If you find something doesn't work as expected, or
deviates from the [numpydoc style guide](https://numpydoc.readthedocs.io/en/latest/format.html)
in an unreasonable way, please feel free to submit a pull request.

Note that this package does deviate from the numpydoc style guide
under some circumstances. For example, if a function does not have
any type annotations, then there will be no type information in the
docstring. The rationale for this is that all type information, if
provided, should be provided through type annotations. However, some
functions may choose not to annotate types for some or all parameters,
but we still want to document them as best we can.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "numpydoc-decorator",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<3.12",
    "maintainer_email": "",
    "keywords": "",
    "author": "Alistair Miles",
    "author_email": "alimanfoo@googlemail.com",
    "download_url": "https://files.pythonhosted.org/packages/5a/39/15efd77d0343e0f391e6ee43a00004aa992765801dded35bd4799e8c7d4d/numpydoc_decorator-2.1.0.tar.gz",
    "platform": null,
    "description": "# numpydoc_decorator\n\nThis package allows you to build [numpy-style\ndocstrings](https://numpydoc.readthedocs.io/en/latest/format.html#sections)\nprogrammatically and apply them using a decorator. This can be useful\nbecause:\n\n-   Parts of your documentation, such as parameter descriptions, can be\n    shared between functions, avoiding the need to repeat yourself.\n\n-   Type information for parameters and return values is automatically\n    picked up from type annotations and added to the docstring, avoiding\n    the need to maintain type information in two places.\n\n## Installation\n\n`pip install numpydoc_decorator`\n\n## Usage\n\n### Documentation a function\n\nHere is an example of documenting a function:\n\n```python\nfrom numpydoc_decorator import doc\n\n\n@doc(\n    summary=\"Say hello to someone.\",\n    extended_summary=\"\"\"\n        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do\n        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad\n        minim veniam, quis nostrud exercitation ullamco laboris nisi ut\n        aliquip ex ea commodo consequat. Duis aute irure dolor in\n        reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla\n        pariatur. Excepteur sint occaecat cupidatat non proident, sunt in\n        culpa qui officia deserunt mollit anim id est laborum.\n    \"\"\",\n    parameters=dict(\n        name=\"The name of the person to greet.\",\n        language=\"The language in which to greet as an ISO 639-1 code.\",\n    ),\n    returns=\"A pleasant greeting.\",\n    raises=dict(\n        NotImplementedError=\"If the requested language has not been implemented yet.\",\n        ValueError=\"If the language is not a valid ISO 639-1 code.\"\n    ),\n    see_also=dict(\n        print=\"You could use this function to print your greeting.\",\n    ),\n    notes=\"\"\"\n        This function is useful when greeting someone else. If you would\n        like something to talk about next, you could try [1]_.\n    \"\"\",\n    references={\n        \"1\": \"\"\"\n            O. McNoleg, \"The integration of GIS, remote sensing, expert systems\n            and adaptive co-kriging for environmental habitat modelling of the\n            Highland Haggis using object-oriented, fuzzy-logic and neural-\n            network techniques,\" Computers & Geosciences, vol. 22, pp. 585-588,\n            1996.\n        \"\"\",\n    },\n    examples=\"\"\"\n        Here is how to greet a friend in English:\n\n        >>> print(greet(\"Ford Prefect\"))\n        Hello Ford Prefect!\n\n        Here is how to greet someone in another language:\n\n        >>> print(greet(\"Tricia MacMillan\", language=\"fr\"))\n        Salut Tricia MacMillan!\n\n    \"\"\",\n)\ndef greet(\n    name: str,\n    language: str = \"en\",\n) -> str:\n    if len(language) != 2:\n        raise ValueError(\"language must be an ISO 639-1 code\")\n    if language == \"en\":\n        return f\"Hello {name}!\"\n    elif language == \"fr\":\n        return f\"Salut {name}!\"\n    else:\n        raise NotImplementedError(f\"language {language} not implemented\")\n```\n\nHere is the docstring that will be created and attached to the\ndecorated function:\n\n```\n>>> print(greet.__doc__)\n\nSay hello to someone.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do\neiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad\nminim veniam, quis nostrud exercitation ullamco laboris nisi ut\naliquip ex ea commodo consequat. Duis aute irure dolor in\nreprehenderit in voluptate velit esse cillum dolore eu fugiat nulla\npariatur. Excepteur sint occaecat cupidatat non proident, sunt in\nculpa qui officia deserunt mollit anim id est laborum.\n\nParameters\n----------\nname : str\n    The name of the person to greet.\nlanguage : str, optional, default: 'en'\n    The language in which to greet as an ISO 639-1 code.\n\nReturns\n-------\nstr\n    A pleasant greeting.\n\nRaises\n------\nNotImplementedError\n    If the requested language has not been implemented yet.\nValueError\n    If the language is not a valid ISO 639-1 code.\n\nSee Also\n--------\nprint : You could use this function to print your greeting.\n\nNotes\n-----\nThis function is useful when greeting someone else. If you would like\nsomething to talk about next, you could try [1]_.\n\nReferences\n----------\n.. [1] O. McNoleg, \"The integration of GIS, remote sensing, expert systems\n    and adaptive co-kriging for environmental habitat modelling of the\n    Highland Haggis using object-oriented, fuzzy-logic and neural- network\n    techniques,\" Computers & Geosciences, vol. 22, pp. 585-588, 1996.\n\nExamples\n--------\nHere is how to greet a friend in English:\n\n>>> print(greet(\"Ford Prefect\"))\nHello Ford Prefect!\n\nHere is how to greet someone in another language:\n\n>>> print(greet(\"Tricia MacMillan\", language=\"fr\"))\nSalut Tricia MacMillan!\n\n```\n\n### Shared parameters\n\nIf you have parameters which are common to multiple functions, here\nis an approach you can take:\n\n```python\nfrom numpydoc_decorator import doc\nfrom typing_extensions import Annotated\n\n\nclass params:\n    name = Annotated[str, \"The name of a person.\"]\n    language = Annotated[str, \"An ISO 639-1 language code.\"]\n\n\n@doc(\n    summary=\"Say hello to someone you know.\",\n    returns=\"A personal greeting.\",\n)\ndef say_hello(\n    name: params.name,\n    language: params.language,\n) -> str:\n    pass\n\n\n@doc(\n    summary=\"Say goodbye to someone you know.\",\n    returns=\"A personal parting.\",\n)\ndef say_goodbye(\n    name: params.name,\n    language: params.language,\n) -> str:\n    pass\n```\n\nHere are the generated docstrings:\n\n```\n>>> print(say_hello.__doc__)\n\nSay hello to someone you know.\n\nParameters\n----------\nname : str\n    The name of a person.\nlanguage : str\n    An ISO 639-1 language code.\n\nReturns\n-------\nstr\n    A personal greeting.\n```\n\n```\n>>> print(say_goodbye.__doc__)\n\nSay goodbye to someone you know.\n\nParameters\n----------\nname : str\n    The name of a person.\nlanguage : str\n    An ISO 639-1 language code.\n\nReturns\n-------\nstr\n    A personal parting.\n```\n\n## Notes\n\nThere are probably lots of edge cases that this package has not\ncovered yet. If you find something doesn't work as expected, or\ndeviates from the [numpydoc style guide](https://numpydoc.readthedocs.io/en/latest/format.html)\nin an unreasonable way, please feel free to submit a pull request.\n\nNote that this package does deviate from the numpydoc style guide\nunder some circumstances. For example, if a function does not have\nany type annotations, then there will be no type information in the\ndocstring. The rationale for this is that all type information, if\nprovided, should be provided through type annotations. However, some\nfunctions may choose not to annotate types for some or all parameters,\nbut we still want to document them as best we can.\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "",
    "version": "2.1.0",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f60548d27efb5fbf88bb2789227e5d04a5f783a92b759cca1bfdef7893ed77ad",
                "md5": "92e92a5cc8e32a8ca99b33f1b601e061",
                "sha256": "25895238de2e11e2c51b76b27d7f539da64920a9333b340732120ecb53f2ef82"
            },
            "downloads": -1,
            "filename": "numpydoc_decorator-2.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "92e92a5cc8e32a8ca99b33f1b601e061",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<3.12",
            "size": 11193,
            "upload_time": "2023-05-25T21:42:11",
            "upload_time_iso_8601": "2023-05-25T21:42:11.797314Z",
            "url": "https://files.pythonhosted.org/packages/f6/05/48d27efb5fbf88bb2789227e5d04a5f783a92b759cca1bfdef7893ed77ad/numpydoc_decorator-2.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5a3915efd77d0343e0f391e6ee43a00004aa992765801dded35bd4799e8c7d4d",
                "md5": "021eb4233b10c3cb675afb8089797aff",
                "sha256": "880e4dcf634aa36fd4815051e21f79c8a370c3bcd5ba1fa5fb9a6e27222d4b8c"
            },
            "downloads": -1,
            "filename": "numpydoc_decorator-2.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "021eb4233b10c3cb675afb8089797aff",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<3.12",
            "size": 11072,
            "upload_time": "2023-05-25T21:42:13",
            "upload_time_iso_8601": "2023-05-25T21:42:13.537776Z",
            "url": "https://files.pythonhosted.org/packages/5a/39/15efd77d0343e0f391e6ee43a00004aa992765801dded35bd4799e8c7d4d/numpydoc_decorator-2.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-25 21:42:13",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "numpydoc-decorator"
}
        
Elapsed time: 0.09816s