Fixes #2688: [Napoleon] Updates to Napoleon documentation to fix intersphinx links and demonstrate PEP 484 type annotations

This commit is contained in:
Rob Ruana
2016-06-23 15:25:00 -04:00
parent 5bd76815ff
commit 2b60fc2027
5 changed files with 206 additions and 95 deletions

View File

@@ -43,6 +43,39 @@ on the first line, separated by a colon.
"""
def function_with_types_in_docstring(param1, param2):
"""Example function with types documented in the docstring.
`PEP 484`_ type annotations are supported. If attribute, parameter, and
return types are annotated according to `PEP 484`_, they do not need to be
included in the docstring:
Args:
param1 (int): The first parameter.
param2 (str): The second parameter.
Returns:
bool: The return value. True for success, False otherwise.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
"""Example function with PEP 484 type annotations.
Args:
param1: The first parameter.
param2: The second parameter.
Returns:
The return value. True for success, False otherwise.
"""
def module_level_function(param1, param2=None, *args, **kwargs):
"""This is an example of a module level function.
@@ -50,9 +83,6 @@ def module_level_function(param1, param2=None, *args, **kwargs):
of each parameter is required. The type and description of each parameter
is optional, but should be included if not obvious.
Parameter types -- if given -- should be specified according to
`PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.
If \*args or \*\*kwargs are accepted,
they should be listed as ``*args`` and ``**kwargs``.
@@ -67,7 +97,7 @@ def module_level_function(param1, param2=None, *args, **kwargs):
Args:
param1 (int): The first parameter.
param2 (Optional[str]): The second parameter. Defaults to None.
param2 (:obj:`str`, optional): The second parameter. Defaults to None.
Second line of description should be indented.
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
@@ -94,10 +124,6 @@ def module_level_function(param1, param2=None, *args, **kwargs):
that are relevant to the interface.
ValueError: If `param2` is equal to `param1`.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
if param1 == param2:
raise ValueError('param1 may not be equal to param2')
@@ -139,7 +165,7 @@ class ExampleError(Exception):
Args:
msg (str): Human readable string describing the exception.
code (Optional[int]): Error code.
code (:obj:`int`, optional): Error code.
Attributes:
msg (str): Human readable string describing the exception.
@@ -163,16 +189,9 @@ class ExampleClass(object):
Properties created with the ``@property`` decorator should be documented
in the property's getter method.
Attribute and property types -- if given -- should be specified according
to `PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.
Attributes:
attr1 (str): Description of `attr1`.
attr2 (Optional[int]): Description of `attr2`.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
attr2 (:obj:`int`, optional): Description of `attr2`.
"""
@@ -190,20 +209,20 @@ class ExampleClass(object):
Args:
param1 (str): Description of `param1`.
param2 (Optional[int]): Description of `param2`. Multiple
param2 (:obj:`int`, optional): Description of `param2`. Multiple
lines are supported.
param3 (List[str]): Description of `param3`.
param3 (:obj:`list` of :obj:`str`): Description of `param3`.
"""
self.attr1 = param1
self.attr2 = param2
self.attr3 = param3 #: Doc comment *inline* with attribute
#: List[str]: Doc comment *before* attribute, with type specified
#: list of str: Doc comment *before* attribute, with type specified
self.attr4 = ['attr4']
self.attr5 = None
"""Optional[str]: Docstring *after* attribute, with type specified."""
"""str: Docstring *after* attribute, with type specified."""
@property
def readonly_property(self):
@@ -212,8 +231,8 @@ class ExampleClass(object):
@property
def readwrite_property(self):
"""List[str]: Properties with both a getter and setter should only
be documented in their getter method.
""":obj:`list` of :obj:`str`: Properties with both a getter and setter
should only be documented in their getter method.
If the setter method contains notable behavior, it should be
mentioned here.

View File

@@ -53,6 +53,52 @@ on the first line, separated by a colon.
"""
def function_with_types_in_docstring(param1, param2):
"""Example function with types documented in the docstring.
`PEP 484`_ type annotations are supported. If attribute, parameter, and
return types are annotated according to `PEP 484`_, they do not need to be
included in the docstring:
Parameters
----------
param1 : int
The first parameter.
param2 : str
The second parameter.
Returns
-------
bool
True if successful, False otherwise.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
"""Example function with PEP 484 type annotations.
The return type must be duplicated in the docstring to comply
with the NumPy docstring style.
Parameters
----------
param1
The first parameter.
param2
The second parameter.
Returns
-------
bool
True if successful, False otherwise.
"""
def module_level_function(param1, param2=None, *args, **kwargs):
"""This is an example of a module level function.
@@ -60,9 +106,6 @@ def module_level_function(param1, param2=None, *args, **kwargs):
The name of each parameter is required. The type and description of each
parameter is optional, but should be included if not obvious.
Parameter types -- if given -- should be specified according to
`PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.
If \*args or \*\*kwargs are accepted,
they should be listed as ``*args`` and ``**kwargs``.
@@ -82,7 +125,7 @@ def module_level_function(param1, param2=None, *args, **kwargs):
----------
param1 : int
The first parameter.
param2 : Optional[str]
param2 : :obj:`str`, optional
The second parameter.
*args
Variable length argument list.
@@ -114,10 +157,6 @@ def module_level_function(param1, param2=None, *args, **kwargs):
ValueError
If `param2` is equal to `param1`.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
if param1 == param2:
raise ValueError('param1 may not be equal to param2')
@@ -167,7 +206,7 @@ class ExampleError(Exception):
----------
msg : str
Human readable string describing the exception.
code : Optional[int]
code : :obj:`int`, optional
Numeric error code.
Attributes
@@ -195,20 +234,13 @@ class ExampleClass(object):
Properties created with the ``@property`` decorator should be documented
in the property's getter method.
Attribute and property types -- if given -- should be specified according
to `PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.
Attributes
----------
attr1 : str
Description of `attr1`.
attr2 : Optional[int]
attr2 : :obj:`int`, optional
Description of `attr2`.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
def __init__(self, param1, param2, param3):
@@ -228,10 +260,10 @@ class ExampleClass(object):
----------
param1 : str
Description of `param1`.
param2 : List[str]
param2 : :obj:`list` of :obj:`str`
Description of `param2`. Multiple
lines are supported.
param3 : Optional[int]
param3 : :obj:`int`, optional
Description of `param3`.
"""
@@ -239,11 +271,11 @@ class ExampleClass(object):
self.attr2 = param2
self.attr3 = param3 #: Doc comment *inline* with attribute
#: List[str]: Doc comment *before* attribute, with type specified
#: list of str: Doc comment *before* attribute, with type specified
self.attr4 = ["attr4"]
self.attr5 = None
"""Optional[str]: Docstring *after* attribute, with type specified."""
"""str: Docstring *after* attribute, with type specified."""
@property
def readonly_property(self):
@@ -252,8 +284,8 @@ class ExampleClass(object):
@property
def readwrite_property(self):
"""List[str]: Properties with both a getter and setter should only
be documented in their getter method.
""":obj:`list` of :obj:`str`: Properties with both a getter and setter
should only be documented in their getter method.
If the setter method contains notable behavior, it should be
mentioned here.

View File

@@ -186,11 +186,74 @@ not be mixed. Choose one style for your project and be consistent with it.
* :ref:`example_google`
* :ref:`example_numpy`
For Python type annotations, see `PEP 484`_.
Type Annotations
----------------
`PEP 484`_ introduced a standard way to express types in Python code.
This is an alternative to expressing types directly in docstrings.
One benefit of expressing types according to `PEP 484`_ is that
type checkers and IDEs can take advantage of them for static code
analysis.
Google style with Python 3 type annotations::
def func(arg1: int, arg2: str) -> bool:
"""Summary line.
Extended description of function.
Args:
arg1: Description of arg1
arg2: Description of arg2
Returns:
Description of return value
"""
return True
Google style with `Python 2/3 compatible annotations`_::
def func(arg1, arg2):
# type: (int, str) -> bool
"""Summary line.
Extended description of function.
Args:
arg1: Description of arg1
arg2: Description of arg2
Returns:
Description of return value
"""
return True
Google style with types in docstrings::
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Args:
arg1 (int): Description of arg1
arg2 (str): Description of arg2
Returns:
bool: Description of return value
"""
return True
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
.. _Python 2/3 compatible annotations:
https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
Configuration
=============

View File

@@ -51,13 +51,13 @@ class Config(object):
Attributes
----------
napoleon_google_docstring : bool, defaults to True
napoleon_google_docstring : :obj:`bool` (Defaults to True)
True to parse `Google style`_ docstrings. False to disable support
for Google style docstrings.
napoleon_numpy_docstring : bool, defaults to True
napoleon_numpy_docstring : :obj:`bool` (Defaults to True)
True to parse `NumPy style`_ docstrings. False to disable support
for NumPy style docstrings.
napoleon_include_init_with_doc : bool, defaults to False
napoleon_include_init_with_doc : :obj:`bool` (Defaults to False)
True to list ``__init___`` docstrings separately from the class
docstring. False to fall back to Sphinx's default behavior, which
considers the ``__init___`` docstring as part of the class
@@ -73,7 +73,7 @@ class Config(object):
def __init__(self):
# This will NOT be included in the docs
napoleon_include_private_with_doc : bool, defaults to False
napoleon_include_private_with_doc : :obj:`bool` (Defaults to False)
True to include private members (like ``_membername``) with docstrings
in the documentation. False to fall back to Sphinx's default behavior.
@@ -89,7 +89,7 @@ class Config(object):
# This will NOT be included in the docs
pass
napoleon_include_special_with_doc : bool, defaults to False
napoleon_include_special_with_doc : :obj:`bool` (Defaults to False)
True to include special members (like ``__membername__``) with
docstrings in the documentation. False to fall back to Sphinx's
default behavior.
@@ -106,7 +106,7 @@ class Config(object):
# This will NOT be included in the docs
return unicode(self.__class__.__name__)
napoleon_use_admonition_for_examples : bool, defaults to False
napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to False)
True to use the ``.. admonition::`` directive for the **Example** and
**Examples** sections. False to use the ``.. rubric::`` directive
instead. One may look better than the other depending on what HTML
@@ -130,7 +130,7 @@ class Config(object):
This is just a quick example
napoleon_use_admonition_for_notes : bool, defaults to False
napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to False)
True to use the ``.. admonition::`` directive for **Notes** sections.
False to use the ``.. rubric::`` directive instead.
@@ -143,7 +143,7 @@ class Config(object):
--------
:attr:`napoleon_use_admonition_for_examples`
napoleon_use_admonition_for_references : bool, defaults to False
napoleon_use_admonition_for_references : :obj:`bool` (Defaults to False)
True to use the ``.. admonition::`` directive for **References**
sections. False to use the ``.. rubric::`` directive instead.
@@ -151,7 +151,7 @@ class Config(object):
--------
:attr:`napoleon_use_admonition_for_examples`
napoleon_use_ivar : bool, defaults to False
napoleon_use_ivar : :obj:`bool` (Defaults to False)
True to use the ``:ivar:`` role for instance variables. False to use
the ``.. attribute::`` directive instead.
@@ -175,7 +175,7 @@ class Config(object):
Description of `attr1`
napoleon_use_param : bool, defaults to True
napoleon_use_param : :obj:`bool` (Defaults to True)
True to use a ``:param:`` role for each function parameter. False to
use a single ``:parameters:`` role for all the parameters.
@@ -202,7 +202,7 @@ class Config(object):
* **arg2** (*int, optional*) --
Description of `arg2`, defaults to 0
napoleon_use_keyword : bool, defaults to True
napoleon_use_keyword : :obj:`bool` (Defaults to True)
True to use a ``:keyword:`` role for each function keyword argument.
False to use a single ``:keyword arguments:`` role for all the
keywords.
@@ -217,7 +217,7 @@ class Config(object):
--------
:attr:`napoleon_use_param`
napoleon_use_rtype : bool, defaults to True
napoleon_use_rtype : :obj:`bool` (Defaults to True)
True to use the ``:rtype:`` role for the return type. False to output
the return type inline with the description.
@@ -297,20 +297,23 @@ def setup(app):
def _patch_python_domain():
import sphinx.domains.python
from sphinx.domains.python import PyTypedField
import sphinx.locale
l_ = sphinx.locale.lazy_gettext
for doc_field in sphinx.domains.python.PyObject.doc_field_types:
if doc_field.name == 'parameter':
doc_field.names = ('param', 'parameter', 'arg', 'argument')
break
sphinx.domains.python.PyObject.doc_field_types.append(
PyTypedField('keyword', label=l_('Keyword Arguments'),
names=('keyword', 'kwarg', 'kwparam'),
typerolename='obj', typenames=('paramtype', 'kwtype'),
can_collapse=True),
)
try:
from sphinx.domains.python import PyTypedField
except ImportError:
pass
else:
import sphinx.domains.python
import sphinx.locale
l_ = sphinx.locale.lazy_gettext
for doc_field in sphinx.domains.python.PyObject.doc_field_types:
if doc_field.name == 'parameter':
doc_field.names = ('param', 'parameter', 'arg', 'argument')
break
sphinx.domains.python.PyObject.doc_field_types.append(
PyTypedField('keyword', label=l_('Keyword Arguments'),
names=('keyword', 'kwarg', 'kwparam'),
typerolename='obj', typenames=('paramtype', 'kwtype'),
can_collapse=True))
def _process_docstring(app, what, name, obj, options, lines):

View File

@@ -40,31 +40,28 @@ class GoogleDocstring(UnicodeMixin):
Parameters
----------
docstring : str or List[str]
docstring : :obj:`str` or :obj:`list` of :obj:`str`
The docstring to parse, given either as a string or split into
individual lines.
config : Optional[sphinx.ext.napoleon.Config or sphinx.config.Config]
config: :obj:`sphinx.ext.napoleon.Config` or :obj:`sphinx.config.Config`
The configuration settings to use. If not given, defaults to the
config object on `app`; or if `app` is not given defaults to the
a new `sphinx.ext.napoleon.Config` object.
a new :class:`sphinx.ext.napoleon.Config` object.
See Also
--------
:class:`sphinx.ext.napoleon.Config`
Other Parameters
----------------
app : Optional[sphinx.application.Sphinx]
app : :class:`sphinx.application.Sphinx`, optional
Application object representing the Sphinx process.
what : Optional[str]
what : :obj:`str`, optional
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : Optional[str]
name : :obj:`str`, optional
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : Optional[sphinx.ext.autodoc.Options]
options : :class:`sphinx.ext.autodoc.Options`, optional
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
@@ -175,7 +172,7 @@ class GoogleDocstring(UnicodeMixin):
Returns
-------
List[str]
:obj:`list` of :obj:`str`
The lines of the docstring in a list.
"""
@@ -737,31 +734,28 @@ class NumpyDocstring(GoogleDocstring):
Parameters
----------
docstring : str or List[str]
docstring : :obj:`str` or :obj:`list` of :obj:`str`
The docstring to parse, given either as a string or split into
individual lines.
config : Optional[sphinx.ext.napoleon.Config or sphinx.config.Config]
config: :obj:`sphinx.ext.napoleon.Config` or :obj:`sphinx.config.Config`
The configuration settings to use. If not given, defaults to the
config object on `app`; or if `app` is not given defaults to the
a new `sphinx.ext.napoleon.Config` object.
a new :class:`sphinx.ext.napoleon.Config` object.
See Also
--------
:class:`sphinx.ext.napoleon.Config`
Other Parameters
----------------
app : Optional[sphinx.application.Sphinx]
app : :class:`sphinx.application.Sphinx`, optional
Application object representing the Sphinx process.
what : Optional[str]
what : :obj:`str`, optional
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : Optional[str]
name : :obj:`str`, optional
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : Optional[sphinx.ext.autodoc.Options]
options : :class:`sphinx.ext.autodoc.Options`, optional
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
@@ -823,7 +817,7 @@ class NumpyDocstring(GoogleDocstring):
Returns
-------
List[str]
:obj:`list` of :obj:`str`
The lines of the docstring in a list.
"""