sphinx.ext.napoleon
– Suporte para doctrings de estilo NumPy e Google¶
Autor do módulo: Rob Ruana
Adicionado na versão 1.3.
Visão geral¶
Você está cansado de escrever docstrings que se parecem com isso:
:param path: The path of the file to wrap
:type path: str
:param field_storage: The :class:`FileStorage` instance to wrap
:type field_storage: FileStorage
:param temporary: Whether or not to delete the file when the File
instance is destructed
:type temporary: bool
:returns: A buffered writable file descriptor
:rtype: BufferedFileStorage
reStructuredText é ótimo, mas cria visualmente denso, difícil de ler docstrings. Compare a confusão acima com a mesma coisa reescrita de acordo com o Google Python Style Guide:
Args:
path (str): The path of the file to wrap
field_storage (FileStorage): The :class:`FileStorage` instance to wrap
temporary (bool): Whether or not to delete the file when the File
instance is destructed
Returns:
BufferedFileStorage: A buffered writable file descriptor
Muito mais legível, não?
Napoleon é uma extension que permite que o Sphinx analise as documentações de estilo NumPy e Google – o estilo recomendado por Khan Academy.
Napoleon é um pré-processador que analisa docstrings de estilo NumPy e Google e os converte em reStructuredText antes que o Sphinx tente analisá-los. Isso acontece em uma etapa intermediária enquanto o Sphinx está processando a documentação, portanto, não modifica nenhuma das docstrings em seus arquivos de código-fonte reais.
Primeiros passos¶
Depois de configurar o Sphinx para construir seus documentos, habilite napoleon no arquivo
conf.py
do Sphinx:# conf.py # Add napoleon to the extensions list extensions = ['sphinx.ext.napoleon']
Use
sphinx-apidoc
para construir sua documentação da API:$ sphinx-apidoc -f -o docs/source projectdir
Docstrings¶
Napoleon interpreta todas as docstrings que autodoc
pode encontrar, incluindo docstrings em: modules
, classes
, attributes
, methods
, functions
, e variables
. Dentro de cada docstring, as seções formatadas especialmente são analisadas e convertidas em reStructuredText.
Toda a formatação padrão do reStructuredText ainda funciona conforme o esperado.
Seções Docstring¶
Todos os cabeçalhos de seção a seguir são suportados:
Args
(alias de Parameters)Arguments
(alias de Parameters)Attention
Attributes
Caution
Danger
Error
Example
Examples
Hint
Important
Keyword Args
(alias de Keyword Arguments)Keyword Arguments
Methods
Note
Notes
Other Parameters
Parameters
Return
(alias de Returns)Returns
Raise
(apelido de Raises)Raises
References
See Also
Tip
Todo
Warning
Warnings
(alias de Warning)Warn
(apelido de Warns)Warns
Yield
(alias de Yields)Yields
Google vs NumPy¶
Napoleon suporta dois estilos de docstrings: Google e NumPy. A principal diferença entre os dois estilos é que o Google usa indentação para separar seções, enquanto o NumPy usa underscores.
Google style:
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
NumPy style:
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
"""
return True
O estilo NumPy tende a exigir mais espaço vertical, enquanto o estilo do Google tende a usar mais espaço horizontal. O estilo do Google tende a ser mais fácil de ler para docstrings curtas e simples, enquanto o estilo NumPy tende a ser mais fácil de ler para docstrings longas e detalhadas.
A escolha entre estilos é em grande parte estética, mas os dois estilos não devem ser misturados. Escolha um estilo para o seu projeto e seja consistente com ele.
Ver também
Para exemplos completos:
Anotações de Tipos¶
PEP 484 introduziu uma maneira padrão de expressar tipos no código Python. Esta é uma alternativa para expressar tipos diretamente em docstrings. Um benefício de expressar tipos de acordo com PEP 484 é que verificadores de tipos e IDEs podem aproveitá-los para análise de código estático. PEP 484 foi então estendido por PEP 526 que introduziu uma maneira semelhante de anotar variáveis (e atributos).
Estilo do Google com anotações do tipo no Python 3:
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
class Class:
"""Summary line.
Extended description of class
Attributes:
attr1: Description of attr1
attr2: Description of attr2
"""
attr1: int
attr2: str
Estilo do Google com tipos em 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
class Class:
"""Summary line.
Extended description of class
Attributes:
attr1 (int): Description of attr1
attr2 (str): Description of attr2
"""
Nota
Python 2/3 compatible annotations não são atualmente suportados pelo Sphinx e não serão exibidos nos documentos.
Configuração¶
Abaixo estão listadas todas as configurações usadas por napoleon e seus valores padrão. Essas configurações podem ser alteradas no arquivo conf.py
do Sphinx. Certifique-se de que “sphinx.ext.napoleon” esteja ativado em conf.py
:
# conf.py
# Add any Sphinx extension module names here, as strings
extensions = ['sphinx.ext.napoleon']
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_preprocess_types = False
napoleon_type_aliases = None
napoleon_attr_annotations = True
- napoleon_google_docstring¶
- Type:
bool
- Default:
True
True to parse Google style docstrings. False to disable support for Google style docstrings.
- napoleon_numpy_docstring¶
- Type:
bool
- Default:
True
True to parse NumPy style docstrings. False to disable support for NumPy style docstrings.
- napoleon_include_init_with_doc¶
- Type:
bool
- Default:
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 documentation.If True:
def __init__(self): """ This will be included in the docs because it has a docstring """ def __init__(self): # This will NOT be included in the docs
- napoleon_include_private_with_doc¶
- Type:
bool
- Default:
False
True to include private members (like
_membername
) with docstrings in the documentation. False to fall back to Sphinx’s default behavior.If True:
def _included(self): """ This will be included in the docs because it has a docstring """ pass def _skipped(self): # This will NOT be included in the docs pass
- napoleon_include_special_with_doc¶
- Type:
bool
- Default:
True
True to include special members (like
__membername__
) with docstrings in the documentation. False to fall back to Sphinx’s default behavior.If True:
def __str__(self): """ This will be included in the docs because it has a docstring """ return unicode(self).encode('utf-8') def __unicode__(self): # This will NOT be included in the docs return unicode(self.__class__.__name__)
- napoleon_use_admonition_for_examples¶
- Type:
bool
- Default:
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 theme is used.Este fragmento NumPy style será convertido da seguinte forma:
Example ------- This is just a quick example
If True:
.. admonition:: Example This is just a quick example
If False:
.. rubric:: Example This is just a quick example
- napoleon_use_admonition_for_notes¶
- Type:
bool
- Default:
False
True to use the
.. admonition::
directive for Notes sections. False to use the.. rubric::
directive instead.Nota
A seção singular Note sempre será convertida em uma diretiva
.. note::
.Ver também
- napoleon_use_admonition_for_references¶
- Type:
bool
- Default:
False
True to use the
.. admonition::
directive for References sections. False to use the.. rubric::
directive instead.Ver também
- napoleon_use_ivar¶
- Type:
bool
- Default:
False
True to use the
:ivar:
role for instance variables. False to use the.. attribute::
directive instead.Este fragmento NumPy style será convertido da seguinte forma:
Attributes ---------- attr1 : int Description of `attr1`
If True:
:ivar attr1: Description of `attr1` :vartype attr1: int
If False:
.. attribute:: attr1 Description of `attr1` :type: int
- napoleon_use_param¶
- Type:
bool
- Default:
True
True to use a
:param:
role for each function parameter. False to use a single:parameters:
role for all the parameters.Este fragmento NumPy style será convertido da seguinte forma:
Parameters ---------- arg1 : str Description of `arg1` arg2 : int, optional Description of `arg2`, defaults to 0
If True:
:param arg1: Description of `arg1` :type arg1: str :param arg2: Description of `arg2`, defaults to 0 :type arg2: :class:`int`, *optional*
If False:
:parameters: * **arg1** (*str*) -- Description of `arg1` * **arg2** (*int, optional*) -- Description of `arg2`, defaults to 0
- napoleon_use_keyword¶
- Type:
bool
- Default:
True
True to use a
:keyword:
role for each function keyword argument. False to use a single:keyword arguments:
role for all the keywords.Isso se comporta de maneira semelhante ao
napoleon_use_param
. Note que, diferentemente dos docutils,:keyword:
e:param:
não serão tratados da mesma maneira – haverá uma seção argumento nomeado separada, processada da mesma forma que a seção “Parâmetros” (tipo links criados se possível)Ver também
- napoleon_use_rtype¶
- Type:
bool
- Default:
True
True to use the
:rtype:
role for the return type. False to output the return type inline with the description.Este fragmento NumPy style será convertido da seguinte forma:
Returns ------- bool True if successful, False otherwise
If True:
:returns: True if successful, False otherwise :rtype: bool
If False:
:returns: *bool* -- True if successful, False otherwise
- napoleon_preprocess_types¶
- Type:
bool
- Default:
False
True to convert the type definitions in the docstrings as references.
Adicionado na versão 3.2.1.
Alterado na versão 3.5: Pré-processa também as docstrings do estilo do Google.
- napoleon_type_aliases¶
- Type:
dict[str, str] | None
- Default:
None
A mapping to translate type names to other names or references. Works only when
napoleon_use_param = True
.Com:
napoleon_type_aliases = { "CustomType": "mypackage.CustomType", "dict-like": ":term:`dict-like <mapping>`", }
Este trecho de estilo NumPy:
Parameters ---------- arg1 : CustomType Description of `arg1` arg2 : dict-like Description of `arg2`
se torna:
:param arg1: Description of `arg1` :type arg1: mypackage.CustomType :param arg2: Description of `arg2` :type arg2: :term:`dict-like <mapping>`
Adicionado na versão 3.2.
- napoleon_attr_annotations¶
- Type:
bool
- Default:
True
True para permitir o uso de anotações de atributos PEP 526 nas classes. Se um atributo estiver documentado na docstring sem um tipo e tiver uma anotação no corpo da classe, esse tipo será usado.
Adicionado na versão 3.4.
- napoleon_custom_sections¶
- Type:
Sequence[str | tuple[str, str]] | None
- Default:
None
Add a list of custom sections to include, expanding the list of parsed sections.
As entradas podem ser strings ou tuplas, dependendo da intenção:
Para criar uma seção “genérica” personalizada, basta passar uma string.
Para criar um alias para uma seção existente, passe uma tupla contendo o nome do alias e o original, nessa ordem.
Para criar uma seção personalizada que seja exibida como a seção de parâmetros ou de retornos, passe uma tupla contendo o nome da seção personalizada e um valor de string, “params_style” ou “returns_style”.
Se uma entrada for apenas uma string, ela será interpretada como um cabeçalho para uma seção genérica. Se a entrada for um contêiner de tupla/lista/indexado, a primeira entrada será o nome da seção, a segunda será a chave de seção a ser emulada. Se o segundo valor de entrada for “params_style” ou “returns_style”, a seção personalizada será exibida como a seção de parâmetros ou a seção de retornos.
Adicionado na versão 1.8.
Alterado na versão 3.5: Suporte a
params_style
areturns_style