sphinx.ext.autodoc
- Inclui documentação das docstrings¶
Essa extensão pode importar módulos que estão sendo documentados, e carregar na documentação a partir de docstrings de forma semiautomática.
Aviso
autodoc
imports the modules to be documented.
If any modules have side effects on import,
these will be executed by autodoc
when sphinx-build is run.
If you document scripts (as opposed to library modules),
make sure that the main routine is protected by
an if __name__ == '__main__'
condition.
For this to work, the docstrings must of course be written in correct reStructuredText. You can then use all of the usual Sphinx markup in the docstrings, and it will end up correctly in the documentation. Together with hand-written documentation, this technique eases the pain of having to maintain two locations for documentation, while at the same time avoiding auto-generated-looking pure API documentation.
If you prefer NumPy or Google style docstrings over reStructuredText,
you can also enable the napoleon
extension.
napoleon
is a preprocessor that converts docstrings
to correct reStructuredText before autodoc
processes them.
Primeiros passos¶
Configuração¶
Activate the plugin by adding 'sphinx.ext.autodoc'
to
the extensions
list in conf.py
:
extensions = [
...
'sphinx.ext.autodoc',
]
Garantir que o código possa ser importado¶
autodoc
analyses the code and docstrings
by introspection after importing the modules.
For importing to work, you have to make sure that your modules can be found
by Sphinx and that dependencies can be resolved
(if your module does import foo
, but foo
is not available
in the python environment that Sphinx runs in, your module import will fail).
Existem duas maneiras de garantir isso:
Use an environment that contains your package and Sphinx. This can e.g. be your local development environment (with an editable install), or an environment in CI in which you install Sphinx and your package. The regular installation process ensures that your package can be found by Sphinx and that all dependencies are available.
Alternativamente, é possível corrigir a execução do Sphinx para que ele possa operar diretamente nas fontes; por exemplo, se você quiser fazer uma construção de Sphinx a partir de um checkout local de fontes.
Patch
sys.path
inconf.py
to include your source path. For example if you have a repository structure withdoc/conf.py
and your package is atsrc/my_package
, then you should add the following to yourconf.py
.import sys from pathlib import Path sys.path.insert(0, str(Path('..', 'src').resolve()))
To cope with missing dependencies, specify the missing modules in the
autodoc_mock_imports
setting.
Uso¶
You can now use the Diretivas to add formatted documentation
for Python code elements like functions, classes, modules, etc.
For example, to document the function io.open()
,
reading its signature and docstring from the source file, you’d write:
.. autofunction:: io.open
You can also document whole classes or even modules automatically, using member options for the auto directives, like:
.. automodule:: io
:members:
Dica
As a hint to autodoc extension, you can put a ::
separator
between the module name and the object name
to let autodoc know the correct module, if it is ambiguous:
.. autoclass:: module.name::Noodle
Marking objects as public or private¶
autodoc considera um membro privado se sua docstring contém
:meta private:
em sua Listas de campos de informações. Por exemplo:def my_function(my_arg, my_other_arg): """blah blah blah :meta private: """
Adicionado na versão 3.0.
autodoc considera um membro público se sua docstring contém
:meta public:
em sua Listas de campos de informações, mesmo se começar com um sublinhado. Por exemplo:def _my_function(my_arg, my_other_arg): """blah blah blah :meta public: """
Adicionado na versão 3.1.
autodoc considera que um membro variável não tem nenhum valor padrão se sua docstring contém
:meta hide-value:
em sua Listas de campos de informações. Exemplo:var1 = None #: :meta hide-value:
Adicionado na versão 3.5.
Doc comments and docstrings¶
Python has no built-in support for docstrings for
module data members or class attributes.
To allow documenting these, autodoc
recognises a special format of
comment called a ‘doc comment’ or ‘documentation comment’.
These comments start with a colon and an optional space character,
'#:'
or '#: '
.
To be recognised, the comments must appear either on the same line
as the variable or on one or more lines before the variable.
Multi-line doc-comments must always appear on the lines before the
variable’s definition.
For example, all three of the following variables have valid doc-comments:
egg_and_spam = 1.50 #: A simple meal
#: Spam! Lovely spam! Lovely spam!
egg_bacon_sausage_and_spam = 2.49
#: Truly gourmet cuisine for madam; Lobster Thermidor
#: aux Crevettes with a mornay sauce garnished with
#: truffle pate, brandy and a fried egg on top and spam.
lobster_thermidor = 35.00
Alternatively, autodoc
can recognise a docstring
on the line immediately following the definition.
In the the following class definition,
all attributes have documentation recognised by autodoc
:
class Foo:
"""Docstring for class Foo."""
#: Doc comment for class attribute Foo.bar.
#: It can have multiple lines.
bar = 1
flox = 1.5 #: Doc comment for Foo.flox. One line only.
baz = 2
"""Docstring for class attribute Foo.baz."""
def __init__(self):
#: Doc comment for instance attribute qux.
self.qux = 3
self.spam = 4
"""Docstring for instance attribute spam."""
Diretivas¶
autodoc
provides several directives that are versions of
the usual py:module
, py:class
and so forth.
On parsing time, they import the corresponding module
and extract the docstring of the given objects,
inserting them into the page source under a suitable
py:module
, py:class
etc. directive.
Nota
Just as py:class
respects the current
py:module
, autoclass
will also do so.
Likewise, automethod
will respect the current py:class
.
Default directive options¶
To make any of the options described below the default,
use the autodoc_default_options
dictionary in conf.py
.
If using defaults for the :members:
, :exclude-members:
,
:private-members:
, or :special-members:
options,
setting the option on a directive will override the default.
Instead, to extend the default list with the per-directive option,
the list may be prepended with a plus sign (+
),
as follows:
.. autoclass:: Noodle
:members: eat
:private-members: +_spicy, _garlickly
Dica
If using autodoc_default_options
,
the defaults can be disabled per-directive with the negated form,
:no-option:
as an option of the directive
For example:
.. automodule:: foo
:no-undoc-members:
Automatically document modules¶
- .. automodule::¶
Document a module. By default, the directive only inserts the docstring of the module itself:
.. automodule:: noodles
will produce source like this:
.. py:module:: noodles The noodles module.
The directive can also contain content of its own, which will be inserted into the resulting non-auto directive source after the docstring (but before any automatic member documentation).
Therefore, you can also mix automatic and non-automatic member documentation, as follows:
.. automodule:: noodles :members: Noodle .. py:function:: boiled_noodle(time=10) Create a noodle that has been boiled for *time* minutes.
Opções
- :no-index:¶
Do not generate an index entry for the documented module or any auto-documented members.
Adicionado na versão 0.4.
- :no-index-entry:¶
Do not generate an index entry for the documented module or any auto-documented members. Unlike
:no-index:
, cross-references are still created.Adicionado na versão 8.2.
- :platform: platforms (comma separated list)¶
Indicate platforms on which the module is available. This is identical to
py:module
’s:platform:
option.
- :synopsis: purpose (text)¶
A sentence describing the module’s purpose. This is identical to
py:module
’s:synopsis:
option.Adicionado na versão 0.5.
- :deprecated:¶
Mark a module as deprecated. This is identical to
py:module
’s:deprecated:
option.Adicionado na versão 0.5.
- :ignore-module-all: (no value)¶
Do not use
__all__
when analysing the module to document.Adicionado na versão 1.7.
Options for selecting members to document
- :members: (no value or comma separated list)¶
Generate automatic documentation for all members of the target module:
.. automodule:: noodles :members:
By default,
autodoc
only includes public members with a docstring or doc-comment (#:
). If__all__
exists, it will be used to define which members are public, unless the:ignore-module-all:
option is set.To only document certain members, an explicit comma-separated list may be used as the argument to
:members:
:.. automodule:: noodles :members: Noodle
- :exclude-members: (comma separated list)¶
Exclude the given names from the members to document. For example:
.. automodule:: noodles :members: :exclude-members: NoodleBase
Adicionado na versão 0.6.
- :imported-members: (no value)¶
To prevent documentation of imported classes or functions, in an
automodule
directive with themembers
option set, only module members where the__module__
attribute is equal to the module name given toautomodule
will be documented.Set the
imported-members
option if you want to prevent this behavior and document all available members.Note that attributes from imported modules will not be documented, because attribute documentation is discovered by parsing the source file of the current module.
Adicionado na versão 1.2.
- :undoc-members:¶
Generate automatic documentation for members of the target module that don’t have a docstring or doc-comment. For example:
.. automodule:: noodles :members: :undoc-members:
- :private-members: (no value or comma separated list)¶
Generate automatic documentation for private members of the target module. This includes names with a leading underscore (e.g.
_private
) and those members explicitly marked as private with:meta private:
... automodule:: noodles :members: :private-members:
To only document certain private members, an explicit comma-separated list may be used as the argument to
:private-members:
:.. automodule:: noodles :members: :private-members: _spicy, _garlickly
Adicionado na versão 1.1.
Alterado na versão 3.2: The option can now take a comma-separated list of arguments.
- :special-members: (no value or comma separated list)¶
Generate automatic documentation for special members of the target module, also known as ‘dunder’ names. This includes all names enclosed with a double-underscore, e.g.
__special__
:.. automodule:: my.Class :members: :special-members:
To only document certain special members, an explicit comma-separated list may be used as the argument to
:special-members:
:.. automodule:: noodles :members: :special-members: __version__
Adicionado na versão 1.1.
Alterado na versão 1.2: The option can now take a comma-separated list of arguments.
Options for documented members
- :member-order: (alphabetical, bysource, or groupwise)¶
Choose the ordering of automatically documented members (default:
alphabetical
). This overrides theautodoc_member_order
setting.alphabetical
: Use simple alphabetical order.groupwise
: Group by object type (class, function, etc), use alphabetical order within groups.bysource
: Use the order of objects in the module’s source. The__all__
variable can be used to override this order.
Observe que, para a ordem de origem, o módulo deve ser um módulo Python com o código-fonte disponível.
Adicionado na versão 0.6.
Alterado na versão 1.0: Support the
'bysource'
option.
- :show-inheritance: (no value)¶
Enable the
:show-inheritance:
option for all members of the module, if:members:
is enabled.Adicionado na versão 0.4.
Automatically document classes or exceptions¶
- .. autoclass::¶
- .. autoexception::¶
Document a class. For exception classes, prefer
.. autoexception::
. By default, the directive only inserts the docstring of the class itself:.. autoclass:: noodles.Noodle
will produce source like this:
.. py:class:: Noodle The Noodle class's docstring.
The directive can also contain content of its own, which will be inserted into the resulting non-auto directive source after the docstring (but before any automatic member documentation).
Therefore, you can also mix automatic and non-automatic member documentation, as follows:
.. autoclass:: noodles.Noodle :members: eat, slurp .. py:method:: boil(time=10) Boil the noodle for *time* minutes.
Advanced usage
It is possible to override the signature for explicitly documented callable objects (functions, methods, classes) with the regular syntax that will override the signature gained from introspection:
.. autoclass:: noodles.Noodle(type) .. automethod:: eat(persona)
Isso é útil se a assinatura do método estiver oculta por um decorador.
Adicionado na versão 0.4.
Opções
- :no-index:¶
Do not generate an index entry for the documented class or any auto-documented members.
Adicionado na versão 0.4.
- :no-index-entry:¶
Do not generate an index entry for the documented class or any auto-documented members. Unlike
:no-index:
, cross-references are still created.Adicionado na versão 8.2.
- :class-doc-from: (class, init, or both)¶
Select which docstring will be used for the main body of the directive. This overrides the global value of
autoclass_content
. The possible values are:class
: Only use the class’s docstring. The__init__()
method can be separately documented using the:members:
option orautomethod
.init
: Only use the docstring of the__init__()
method.both
: Use both, appending the docstring of the__init__()
method to the class’s docstring.
If the
__init__()
method doesn’t exist or has a blank docstring,autodoc
will attempt to use the__new__()
method’s docstring, if it exists and is not blank.Adicionado na versão 4.1.
Options for selecting members to document
- :members: (no value or comma separated list)¶
Generate automatic documentation for all members of the target class:
.. autoclass:: noodles.Noodle :members:
By default,
autodoc
only includes public members with a docstring or doc-comment (#:
) that are attributes of the target class (i.e. not inherited).To only document certain members, an explicit comma-separated list may be used as the argument to
:members:
:.. autoclass:: noodles.Noodle :members: eat, slurp
- :exclude-members: (comma separated list)¶
Exclude the given names from the members to document. For example:
.. autoclass:: noodles.Noodle :members: :exclude-members: prepare
Adicionado na versão 0.6.
- :inherited-members: (comma separated list)¶
To generate automatic documentation for members inherited from base classes, use the
:inherited-members:
option:.. autoclass:: noodles.Noodle :members: :inherited-members:
This can be combined with the
:undoc-members:
option to generate automatic documentation for all available members of the class.The members of classes listed in the argument to
:inherited-members:
are excluded from the automatic documentation. This defaults toobject
if no argument is provided, meaning that members of theobject
class are not documented. To include these, useNone
as the argument.For example; If your class
MyList
is derived fromlist
class and you don’t want to documentlist.__len__()
, you should specify a option:inherited-members: list
to avoid special members of list class.Nota
Should any of the inherited members use a format other than reStructuredText for their docstrings, there may be markup warnings or errors.
Adicionado na versão 0.3.
Alterado na versão 3.0:
:inherited-members:
now takes the name of a base class to exclude as an argument.Alterado na versão 5.0: A comma separated list of base class names can be used.
- :undoc-members: (no value)¶
Generate automatic documentation for members of the target class that don’t have a docstring or doc-comment. For example:
.. autoclass:: noodles.Noodle :members: :undoc-members:
- :private-members: (no value or comma separated list)¶
Generate automatic documentation for private members of the target class. This includes names with a leading underscore (e.g.
_private
) and those members explicitly marked as private with:meta private:
... autoclass:: noodles.Noodle :members: :private-members:
To only document certain private members, an explicit comma-separated list may be used as the argument to
:private-members:
:.. autoclass:: noodles.Noodle :members: :private-members: _spicy, _garlickly
Adicionado na versão 1.1.
Alterado na versão 3.2: A opção agora pode receber argumentos.
- :special-members: (no value or comma separated list)¶
Generate automatic documentation for special members of the target class, also known as ‘dunder’ names. This includes all names enclosed with a double-underscore, e.g.
__special__
:.. autoclass:: noodles.Noodle :members: :special-members:
To only document certain special members, an explicit comma-separated list may be used as the argument to
:special-members:
:.. autoclass:: noodles.Noodle :members: :special-members: __init__, __name__
Adicionado na versão 1.1.
Alterado na versão 1.2: The option can now take a comma-separated list of arguments.
Options for documented members
- :member-order: (alphabetical, bysource, or groupwise)¶
Choose the ordering of automatically documented members (default:
alphabetical
). This overrides theautodoc_member_order
setting.'alphabetical'
: Use simple alphabetical order.'groupwise'
: Group by object type (class, function, etc), use alphabetical order within groups.'bysource'
: Use the order of objects in the module’s source. The__all__
variable can be used to override this order.
Observe que, para a ordem de origem, o módulo deve ser um módulo Python com o código-fonte disponível.
Adicionado na versão 0.6.
Alterado na versão 1.0: Support the
'bysource'
option.
- :show-inheritance: (no value)¶
Insert the class’s base classes after the class signature.
Adicionado na versão 0.4.
Automatically document function-like objects¶
- .. autofunction::¶
- .. automethod::¶
- .. autoproperty::¶
- .. autodecorator::¶
Document a function, method, property, or decorator. By default, the directive only inserts the docstring of the function itself:
.. autofunction:: noodles.average_noodle
will produce source like this:
.. py:function:: noodles.average_noodle The average_noodle function's docstring.
The directive can also contain content of its own, which will be inserted into the resulting non-auto directive source after the docstring.
Therefore, you can also mix automatic and non-automatic documentation, as follows:
.. autofunction:: noodles.average_noodle .. note:: For more flexibility, use the :py:class:`!Noodle` class.
Adicionado na versão 2.0:
autodecorator
.Adicionado na versão 2.1:
autoproperty
.Nota
If you document decorated functions or methods, keep in mind that
autodoc
retrieves its docstrings by importing the module and inspecting the__doc__
attribute of the given function or method. That means that if a decorator replaces the decorated function with another, it must copy the original__doc__
to the new function.Advanced usage
It is possible to override the signature for explicitly documented callable objects (functions, methods, classes) with the regular syntax that will override the signature gained from introspection:
.. autoclass:: Noodle(type) .. automethod:: eat(persona)
Isso é útil se a assinatura do método estiver oculta por um decorador.
Adicionado na versão 0.4.
Opções
- :no-index:¶
Do not generate an index entry for the documented function.
Adicionado na versão 0.4.
- :no-index-entry:¶
Do not generate an index entry for the documented function. Unlike
:no-index:
, cross-references are still created.Adicionado na versão 8.2.
Automatically document attributes or data¶
- .. autodata::¶
- .. autoattribute::¶
Document a module level variable or constant (‘data’) or class attribute. By default, the directive only inserts the docstring of the variable itself:
.. autodata:: noodles.FLOUR_TYPE
will produce source like this:
.. py:data:: noodles.FLOUR_TYPE The FLOUR_TYPE constant's docstring.
The directive can also contain content of its own, which will be inserted into the resulting non-auto directive source after the docstring.
Therefore, you can also mix automatic and non-automatic member documentation, as follows:
.. autodata:: noodles.FLOUR_TYPE .. hint:: Cooking time can vary by which flour type is used.
Alterado na versão 0.6:
autodata
eautoattribute
agora podem extrair docstrings.Alterado na versão 1.1: Doc-comments are now allowed on the same line of an assignment.
Opções
- :no-index:¶
Do not generate an index entry for the documented variable or constant.
Adicionado na versão 0.4.
- :no-index-entry:¶
Do not generate an index entry for the documented variable or constant. Unlike
:no-index:
, cross-references are still created.Adicionado na versão 8.2.
- :annotation: value (string)¶
Adicionado na versão 1.2.
By default,
autodoc
attempts to obtain the type annotation and value of the variable by introspection, displaying it after the variable’s name. To override this, a custom string for the variable’s value may be used as the argument toannotation
.For example, if the runtime value of
FILE_MODE
is0o755
, the displayed value will be493
(asoct(493) == '0o755'
). This can be fixed by setting:annotation: = 0o755
.If
:annotation:
is used without arguments, no value or type hint will be shown for the variable.
- :no-value:¶
Adicionado na versão 3.4.
To display the type hint of the variable without a value, use the
:no-value:
option. If both the:annotation:
and:no-value:
options are used,:no-value:
has no effect.
Configuração¶
Existem também valores de configuração que você pode definir:
- autoclass_content¶
- Type:
str
- Default:
'class'
Este valor seleciona qual conteúdo será inserido no corpo principal de uma diretiva
autoclass
. Os valores possíveis são:'class'
Only the class’ docstring is inserted. You can still document
__init__
as a separate method usingautomethod
or themembers
option toautoclass
.'both'
As docstrings da classe e do método
__init__
são concatenadas e inseridas.'init'
Somente a docstring do método
__init__
é inserida.
Adicionado na versão 0.3.
Se a classe não tiver o método
__init__
ou se a docstring do método__init__
estiver vazia, mas a classe tem a docstring do método__new__
, ela é usada no lugar.Adicionado na versão 1.4.
- autodoc_class_signature¶
- Type:
str
- Default:
'mixed'
Este valor seleciona como a assinatura será exibida para a classe definida pela diretiva
autoclass
. Os valores possíveis são:'mixed'
Exibe a assinatura com o nome da classe.
'separated'
Exibe a assinatura como um método.
Adicionado na versão 4.1.
- autodoc_member_order¶
- Type:
str
- Default:
'alphabetical'
Define the order in which
automodule
andautoclass
members are listed. Supported values are:'alphabetical'
: Use alphabetical order.'groupwise'
: order by member type. The order is:for modules, exceptions, classes, functions, data
- for classes: class methods, static methods, methods,
and properties/attributes
Members are ordered alphabetically within groups.
'bysource'
: Use the order in which the members appear in the source code. This requires that the module must be a Python module with the source code available.
Adicionado na versão 0.6.
Alterado na versão 1.0: Suporte para
'bysource'
.
- autodoc_default_options¶
- Type:
dict[str, str | bool]
- Default:
{}
The default options for autodoc directives. They are applied to all autodoc directives automatically. It must be a dictionary which maps option names to the values. For example:
autodoc_default_options = { 'members': 'var1, var2', 'member-order': 'bysource', 'special-members': '__init__', 'undoc-members': True, 'exclude-members': '__weakref__' }
Definir
None
ouTrue
como o valor é equivalente a fornecer apenas o nome da opção às diretivas.The supported options are:
'members'
: Seeautomodule:members
.'undoc-members'
Seeautomodule:undoc-members
.'private-members'
: Seeautomodule:private-members
.'special-members'
: Seeautomodule:special-members
.'inherited-members'
: Seeautoclass:inherited-members
.'imported-members'
: Seeautomodule:imported-members
.'exclude-members'
: Seeautomodule:exclude-members
.'ignore-module-all'
: Seeautomodule:ignore-module-all
.'member-order'
: Seeautomodule:member-order
.'show-inheritance'
: Seeautoclass:show-inheritance
.'class-doc-from'
: Seeautoclass:class-doc-from
.'no-value'
: Seeautodata:no-value
.'no-index'
: Seeautomodule:no-index
.'no-index-entry'
: Seeautomodule:no-index-entry
.
Adicionado na versão 1.8.
Alterado na versão 2.0: Aceita
True
como valor.Alterado na versão 2.1: Adicionado
'imported-members'
.Alterado na versão 4.1: Adicionado
'class-doc-from'
.Alterado na versão 4.5: Adicionado
'no-value'
.
- autodoc_docstring_signature¶
- Type:
bool
- Default:
True
As funções importadas dos módulos
C
não podem ser introspectivas e, portanto, a assinatura dessas funções não pode ser determinada automaticamente. No entanto, é uma convenção frequentemente usada para colocar a assinatura na primeira linha da docstring da função.Se este valor booleano é definido como
True
(que é o padrão), o autodoc irá olhar para a primeira linha da docstring para funções e métodos, e se parecer com uma assinatura, use a linha como assinatura e remova-a do conteúdo da docstring.autodoc continuará a procurar por várias linhas de assinatura, parando na primeira linha que não se parece com uma assinatura. Isso é útil para declarar assinaturas de função sobrecarregadas.
Adicionado na versão 1.1.
Alterado na versão 3.1: Suporte a assinaturas sobrecarregadas
Alterado na versão 4.0: Assinaturas sobrecarregadas não precisam ser separadas por uma barra invertida
- autodoc_mock_imports¶
- Type:
list[str]
- Default:
[]
Este valor contém uma lista de módulos a serem reproduzidos. Isso é útil quando algumas dependências externas não são atendidas no momento da criação e interrompem o processo de construção. Você só pode especificar o pacote raiz das próprias dependências e omitir os submódulos:
autodoc_mock_imports = ['django']
Fará um mock de todas as importações sob o pacote
django
.Adicionado na versão 1.3.
Alterado na versão 1.6: Esse valor de configuração requer apenas para declarar os módulos de nível superior que devem ser mockados.
- autodoc_typehints¶
- Type:
str
- Default:
'signature'
Este valor controla como representar dicas de tipo. A configuração presume os seguintes valores:
'signature'
– Show typehints in the signature'description'
– Mostra dicas de tipo como conteúdo da função ou método As dicas de tipo de funções ou métodos sobrecarregados ainda serão representadas na assinatura.'none'
– Não mostra dicas de tipo'both'
– Mostra dicas de tipo na assinatura e como conteúdo da função ou método
Funções ou métodos sobrecarregados não terão dicas de tipo incluídas na descrição porque é impossível representar com precisão todas as sobrecargas possíveis como uma lista de parâmetros.
Adicionado na versão 2.1.
Adicionado na versão 3.0: A nova opção
'description'
foi adicionada.Adicionado na versão 4.1: A nova opção
'both'
foi adicionada.
- autodoc_typehints_description_target¶
- Type:
str
- Default:
'all'
This value controls whether the types of undocumented parameters and return values are documented when
autodoc_typehints
is set to'description'
. Supported values:'all'
: Types are documented for all parameters and return values, whether they are documented or not.'documented'
: Types will only be documented for a parameter or a return value that is already documented by the docstring.'documented_params'
: Parameter types will only be annotated if the parameter is documented in the docstring. The return type is always annotated (except if it isNone
).
Adicionado na versão 4.0.
Adicionado na versão 5.0: Nova opção
'documented_params'
foi adicionada.
- autodoc_type_aliases¶
- Type:
dict[str, str]
- Default:
{}
A dictionary for users defined type aliases that maps a type name to the full-qualified object name. It is used to keep type aliases not evaluated in the document.
Os aliases de tipo só estão disponíveis se o seu programa habilitar o recurso Avaliação Adiada de Anotações (PEP 563) via
from __future__ import annotations
.For example, there is code using a type alias:
from __future__ import annotations AliasType = Union[List[Dict[Tuple[int, str], Set[int]]], Tuple[str, List[str]]] def f() -> AliasType: ...
If
autodoc_type_aliases
is not set, autodoc will generate internal mark-up from this code as following:.. py:function:: f() -> Union[List[Dict[Tuple[int, str], Set[int]]], Tuple[str, List[str]]] ...
If you set
autodoc_type_aliases
as{'AliasType': 'your.module.AliasType'}
, it generates the following document internally:.. py:function:: f() -> your.module.AliasType: ...
Adicionado na versão 3.3.
- autodoc_typehints_format¶
- Type:
str
- Default:
'short'
Este valor controla o formato das dicas de tipo. A configuração assume os seguintes valores:
'fully-qualified'
– Mostra o nome do módulo e seu nome de dicas de tipo'short'
– Suppress the leading module names of the typehints (e.g.io.StringIO
->StringIO
)
Adicionado na versão 4.4.
Alterado na versão 5.0: A configuração padrão foi alterada para
'short'
- autodoc_preserve_defaults¶
- Type:
bool
- Default:
False
Se for True, os valores de argumento padrão das funções não serão avaliados na geração do documento. Ele os preserva como estão no código-fonte.
Adicionado na versão 4.0: Adicionado como um recurso experimental. Isso será integrado ao autodoc core no futuro.
- autodoc_use_type_comments¶
- Type:
bool
- Default:
True
Attempt to read
# type: ...
comments from source code to supplement missing type annotations, if True.This can be disabled if your source code does not use type comments, for example if it exclusively uses type annotations or does not use type hints of any kind.
Adicionado na versão 8.2: Added the option to disable the use of type comments in via the new
autodoc_use_type_comments
option, which defaults toTrue
for backwards compatibility. The default will change toFalse
in Sphinx 10.
- autodoc_warningiserror¶
- Type:
bool
- Default:
True
This value controls the behavior of
sphinx-build --fail-on-warning
during importing modules. IfFalse
is given, autodoc forcedly suppresses the error if the imported module emits warnings.Alterado na versão 8.1: Esta opção agora não tem efeito, pois
--fail-on-warning
não mais encerra cedo.
- autodoc_inherit_docstrings¶
- Type:
bool
- Default:
True
Este valor controla a herança de docstrings. Se definido como True, a docstring para classes ou métodos, se não for definida explicitamente, é herdada dos pais.
Adicionado na versão 1.7.
- suppress_warnings
- Type:
Sequence[str]
- Default:
()
autodoc
supports suppressing warning messages viasuppress_warnings
. It defines the following additional warnings types:autodoc
autodoc.import_object
Pré-processamento de docstrings¶
autodoc fornece os seguintes eventos adicionais:
- autodoc-process-docstring(app, what, name, obj, options, lines)¶
Adicionado na versão 0.4.
Emitido quando o autodoc leu e processou uma docstring. lines é uma lista de strings – as linhas da docstring processada – que o manipulador de eventos pode modificar in place para alterar o que o Sphinx coloca na saída.
- Parâmetros:
app – o objeto do aplicativo Sphinx
what – the type of the object which the docstring belongs to (one of
'module'
,'class'
,'exception'
,'function'
,'method'
,'attribute'
)name – o nome totalmente qualificado do objeto
obj – o objeto em si
options – as opções dadas à diretiva: um objeto com os atributos
inherited_members
,undoc_members
,show_inheritance
eno-index
que são verdadeiros se a opção de sinalizador com o mesmo nome foi dada à diretiva autolines – as linhas da docstring, veja acima
- autodoc-before-process-signature(app, obj, bound_method)¶
Adicionado na versão 2.4.
Emitido antes do autodoc formatar uma assinatura para um objeto. O manipulador de eventos pode modificar um objeto para alterar sua assinatura.
- Parâmetros:
app – o objeto do aplicativo Sphinx
obj – o objeto em si
bound_method – um booleano indica que um objeto é um método vinculado ou não
- autodoc-process-signature(app, what, name, obj, options, signature, return_annotation)¶
Adicionado na versão 0.5.
Emitido quando o autodoc formatou uma assinatura para um objeto. O manipulador de eventos pode retornar uma nova tupla
(signature, return_annotation)
para alterar o que o Sphinx coloca na saída.- Parâmetros:
app – o objeto do aplicativo Sphinx
what – the type of the object which the docstring belongs to (one of
'module'
,'class'
,'exception'
,'function'
,'method'
,'attribute'
)name – o nome totalmente qualificado do objeto
obj – o objeto em si
options – as opções dadas à diretiva: um objeto com os atributos
inherited_members
,undoc_members
,show_inheritance
eno-index
que são verdadeiros se a opção de sinalizador com o mesmo nome foi dada à diretiva autosignature – function signature, as a string of the form
'(parameter_1, parameter_2)'
, orNone
if introspection didn’t succeed and signature wasn’t specified in the directive.return_annotation – function return annotation as a string of the form
' -> annotation'
, orNone
if there is no return annotation
O módulo sphinx.ext.autodoc
fornece funções de fábrica para o processamento docstring
comumente necessário no evento autodoc-process-docstring
:
- sphinx.ext.autodoc.cut_lines(pre: int, post: int = 0, what: Sequence[str] | None = None) _AutodocProcessDocstringListener [código-fonte]¶
Retorna um “listener” que remove o primeiro pre e as últimas linhas post de cada docstring. Se what for uma sequência de strings, somente as docstrings de um tipo em what serão processadas.
Use assim (por exemplo, na função
setup()
doconf.py
):from sphinx.ext.autodoc import cut_lines app.connect('autodoc-process-docstring', cut_lines(4, what={'module'}))
Isso pode (e deve) ser usado no lugar de
automodule_skip_lines
.
- sphinx.ext.autodoc.between(marker: str, what: Sequence[str] | None = None, keepempty: bool = False, exclude: bool = False) _AutodocProcessDocstringListener [código-fonte]¶
Retorna um “listener” que mantém, ou se exclude for True, linhas entre as linhas que correspondem à expressão regular marker. Se nenhuma linha corresponder, a docstring resultante estará vazia, portanto nenhuma alteração será feita a menos que keepempty seja True.
Se what for uma sequência de strings, somente as docstrings de um tipo em what serão processadas.
- autodoc-process-bases(app, name, obj, options, bases)¶
Emitido quando autodoc leu e processou uma classe para determinar as classes básicas. bases é uma lista de classes que o manipulador de eventos pode modificar no local para alterar o que o Sphinx coloca na saída. É emitido apenas se a opção
show-inheritance
for fornecida.- Parâmetros:
app – o objeto do aplicativo Sphinx
name – o nome totalmente qualificado do objeto
obj – o objeto em si
options – as opções fornecidas para a diretiva da classe
bases – a lista de assinatura de classes base, veja acima.
Adicionado na versão 4.1.
Alterado na versão 4.3:
bases
pode conter uma string como nome de classe base. Ele será processado como texto com marcação reStructuredText.
Ignorando membros¶
O autodoc permite que o usuário defina um método personalizado para determinar se um membro deve ser incluído na documentação usando o seguinte evento:
- autodoc-skip-member(app, what, name, obj, skip, options)¶
Adicionado na versão 0.5.
Emitido quando o autodoc tem que decidir se um membro deve ser incluído na documentação. O membro é excluído se um manipulador retornar
True
. Está incluído se o manipulador retornarFalse
.Se mais de uma extensão ativada manipular o evento
autodoc-skip-member
, o autodoc usará o primeiro valor nãoNone
retornado por um manipulador. Os manipuladores devem retornarNone
para retornar ao comportamento de salto do autodoc e de outras extensões ativadas.- Parâmetros:
app – o objeto do aplicativo Sphinx
what – the type of the object which the docstring belongs to (one of
'module'
,'class'
,'exception'
,'function'
,'method'
,'attribute'
)name – o nome totalmente qualificado do objeto
obj – o objeto em si
skip – um booleano indicando se o autodoc pulará este membro se o manipulador de usuário não substituir a decisão
options – as opções dadas à diretiva: um objeto com os atributos
inherited_members
,undoc_members
,show_inheritance
eno-index
que são verdadeiros se a opção de sinalizador com o mesmo nome foi dada à diretiva auto