jump to navigation

Domínios Sphinx¶ 2011/02/01

Posted by gsavix in colaboração na aquisição conhecimento, como gerar documentos a partir dos programas fonte, como publicar na internet gratuitamente, Conhecimento, Conhecimento para receber ou transferir tecnologia, gerador documentos, língua portuguesa, Memorando, metodologia para receber ou transferir conhecimento, publicação jornal internet, publicador documentação, sociologia do conhecimento.
trackback

Domínios Sphinx

Novo na versão 1.0.

O que é um Domínio?

Originalmente o Sphinx foi concebido para um objetivo simples, documentação da Linguagem Python. Ele foi disponibilizado para todos como uma ferramenta de documentação, mas a documentação de módulos Python permanecia inerentemente arraigada – as mais fundamentais diretivas, como function, foram desenhadas para lidar objetos Python. Desde que Sphinx tornou-se mais popular, aumentou o interesse para diferentes propósitos como: projetos C/C++ projetos JavaScript, ou mesmo como marcação reStructuredText (como nesta documentação por exemplo).

Isto era possível, porém agora ficou mais fácil utilizá-lo em projetos de documentação usando diferentes linguagens de programação ou mesmo em uma que não seja suportada pela distribuição Sphinx, pois foi criado a diretiva domínio (domain) para esta finalidade.

O domínio (domain) é uma coleção de marcações (reStructuredText diretiva e role) para descrever e ligar o object juntos. Ex. elementos de uma linguagem de programação. Os nomes e diretivas num domínio são parecidos com: domain:name, ex. py:function. Domínios também podem prover índices personalizados (como Python Module Index).

Usando domínios significa que não haverá problemas quando alguém quiser fazer referência a classes C++ e Python. Isto também significa que estensões que suportam novas linguagens são muito mais faceis de serem escritas.

Esta seção descreve quais domínios vem com o Sphinx. O domínio API é bem documentado, na seção Domain API.

Marcação Básica

Muitos domínios trazem um número de diretivas descrição de objetos, usadas para prover descrição específica para objetos dos módulos. Cada diretiva requer uma ou mais assinaturas par prover informação básica sobre o que está sendo descrito e o conteúdo pode ser a descrição. A versão básica cria entradas no índice geral; Se nenhuma entrada no índice é desejada, você pode usar a opção de diretiva :noindex:. Um exemplo usando diretiva domínio Python:

.. py:function:: spam(eggs)
                 ham(eggs)

   Spam or ham the foo.

Isto descreve as duas funções Python spam e ham. (Note que quando as assinaturas se tornam longas, você pode quebrá-las se você adicionar uma barra invertida em linhas que deverão ser continuadas na próxima linha. Ex:

.. py:function:: filterwarnings(action, message='', category=Warning, \
                                module='', lineno=0, append=False)
   :noindex:

(Este exemplo também mostra o uso de :noindex:)

Domínios também permitem o uso de “roles” que façam ligações com estas descrições de objetos. Por exemplo, para criar ligação para uma das funções descritas acima você pode usar

A função :py:func:`spam` faz a mesma coisa.

Como você pode ver, ambos nomes de diretiva e role contêm o nome do domínio e o nome da diretiva.

Domínio Padrão

Para evitar escrever o domínio toda vez que você descreve Objetos Python, um domínio padrão pode ser selecionado com o valor config primary_domain ou com esta diretiva:

.. default-domain:: nome
Selecione um novo domínio. Enquanto o primary_domain seleciona um padrão global, este tem efeito só dentro do mesmo arquivo.

Se nenhum outro padrão é selecionado, o domínio Python (chamado py) é o padrão, mais por compatibilidade com antigas versões do Sphinx.

Diretivas e roles que pertencem ao mesmo dominio padrão, podem ser referenciadas sem explicitar o domínio, por exemplo

.. function:: pyfunc()

   Descreve uma função Python.

Referência a :func:`pyfunc`.

Sintaxe Referência-Cruzada

Para roles de referência-cruzada provida por domínios, as mesmas facilidades existem como referências-cruzadas gerais. Veja Cross-referencing syntax.

Resumidamente:

  • Voce pode explicitar um título e uma referência alvo: :role:`title <target>` irá referenciar a target, mas a ligação texto será title.
  • Se prefixar o conteúdo com !, nenhuma referência ou hiperligação será criada.
  • Se você prefixar o conteúdo com ~, o texto de ligação será só o último componente do alvo. Por exemplo: :py:meth:`~Queue.Queue.get` irá referenciar a Queue.Queue.get mas só irá exibir get com texto da ligação.

O Domínio Python

The Python domain (name py) provides the following directives for module declarations:

.. py:module:: name
This directive marks the beginning of the description of a module (or package submodule, in which case the name should be fully qualified, including the package name). It does not create content (like e.g. py:class does).

This directive will also cause an entry in the global module index.

The platform option, if present, is a comma-separated list of the platforms on which the module is available (if it is available on all platforms, the option should be omitted). The keys are short identifiers; examples that are in use include “IRIX”, “Mac”, “Windows”, and “Unix”. It is important to use a key which has already been used when applicable.

The synopsis option should consist of one sentence describing the module’s purpose – it is currently only used in the Global Module Index.

The deprecated option can be given (with no value) to mark a module as deprecated; it will be designated as such in various locations then.

.. py:currentmodule:: name
This directive tells Sphinx that the classes, functions etc. documented from here are in the given module (like py:module), but it will not create index entries, an entry in the Global Module Index, or a link target for py:mod. This is helpful in situations where documentation for things in a module is spread over multiple files or sections – one location has the py:module directive, the others only py:currentmodule.

The following directives are provided for module and class contents:

.. py:data:: name
Describes global data in a module, including both variables and values used as “defined constants.” Class and object attributes are not documented using this environment.

.. py:exception:: name
Describes an exception class. The signature can, but need not include parentheses with constructor arguments.

.. py:function:: name(signature)
Describes a module-level function. The signature should include the parameters, enclosing optional parameters in brackets. Default values can be given if it enhances clarity; see Python Signatures. For example:

.. py:function:: Timer.repeat([repeat=3[, number=1000000]])

Object methods are not documented using this directive. Bound object methods placed in the module namespace as part of the public interface of the module are documented using this, as they are equivalent to normal functions for most purposes.

The description should include information about the parameters required and how they are used (especially whether mutable objects passed as parameters are modified), side effects, and possible exceptions. A small example may be provided.

.. py:class:: name[(signature)]
Describes a class. The signature can include parentheses with parameters which will be shown as the constructor arguments. See also Python Signatures.

Methods and attributes belonging to the class should be placed in this directive’s body. If they are placed outside, the supplied name should contain the class name so that cross-references still work. Example:

.. py:class:: Foo
   .. py:method:: quux()

-- or --

.. py:class:: Bar

.. py:method:: Bar.quux()

The first way is the preferred one.

.. py:attribute:: name
Describes an object data attribute. The description should include information about the type of the data to be expected and whether it may be changed directly.

.. py:method:: name(signature)
Describes an object method. The parameters should not include the self parameter. The description should include similar information to that described for function. See also Python Signatures.

.. py:staticmethod:: name(signature)
Like py:method, but indicates that the method is a static method.

Novo na versão 0.4.

.. py:classmethod:: name(signature)
Like py:method, but indicates that the method is a class method.

Novo na versão 0.6.

Python Signatures

Signatures of functions, methods and class constructors can be given like they would be written in Python, with the exception that optional parameters can be indicated by brackets:

.. py:function:: compile(source[, filename[, symbol]])

It is customary to put the opening bracket before the comma. In addition to this “nested” bracket style, a “flat” style can also be used, due to the fact that most optional parameters can be given independently:

.. py:function:: compile(source[, filename, symbol])

Default values for optional arguments can be given (but if they contain commas, they will confuse the signature parser). Python 3-style argument annotations can also be given as well as return type annotations:

.. py:function:: compile(source : string[, filename, symbol]) -> ast object

Info field lists

Novo na versão 0.4.

Inside Python object description directives, reST field lists with these fields are recognized and formatted nicely:

  • param, parameter, arg, argument, key, keyword: Description of a parameter.
  • type: Type of a parameter.
  • raises, raise, except, exception: That (and when) a specific exception is raised.
  • var, ivar, cvar: Description of a variable.
  • returns, return: Description of the return value.
  • rtype: Return type.

The field names must consist of one of these keywords and an argument (except for returns and rtype, which do not need an argument). This is best explained by an example:

.. py:function:: format_exception(etype, value, tb[, limit=None])

   Format the exception with a traceback.

   :param etype: exception type
   :param value: exception value
   :param tb: traceback object
   :param limit: maximum number of stack frames to show
   :type limit: integer or None
   :rtype: list of strings

This will render like this:

format_exception(etype, value, tb[, limit=None])
Format the exception with a traceback.

Parâmetros:
  • etype – exception type
  • value – exception value
  • tb – traceback object
  • limit (integer or None) – maximum number of stack frames to show
Tipo de retorno:
list of strings

It is also possible to combine parameter type and description, if the type is a single word, like this:

:param integer limit: maximum number of stack frames to show

Cross-referencing Python objects

The following roles refer to objects in modules and are possibly hyperlinked if a matching identifier is found:

:py:mod:
Reference a module; a dotted name may be used. This should also be used for package names.

:py:func:
Reference a Python function; dotted names may be used. The role text needs not include trailing parentheses to enhance readability; they will be added automatically by Sphinx if the add_function_parentheses config value is true (the default).

:py:data:
Reference a module-level variable.

:py:const:
Reference a “defined” constant. This may be a C-language #define or a Python variable that is not intended to be changed.

:py:class:
Reference a class; a dotted name may be used.

:py:meth:
Reference a method of an object. The role text can include the type name and the method name; if it occurs within the description of a type, the type name can be omitted. A dotted name may be used.

:py:attr:
Reference a data attribute of an object.

:py:exc:
Reference an exception. A dotted name may be used.

:py:obj:
Reference an object of unspecified type. Useful e.g. as the default_role.

Novo na versão 0.4.

The name enclosed in this markup can include a module name and/or a class name. For example, :py:func:`filter` could refer to a function named filter in the current module, or the built-in function of that name. In contrast, :py:func:`foo.filter` clearly refers to the filter function in the foo module.

Normally, names in these roles are searched first without any further qualification, then with the current module name prepended, then with the current module and class name (if any) prepended. If you prefix the name with a dot, this order is reversed. For example, in the documentation of Python’s codecs module, :py:func:`open` always refers to the built-in function, while :py:func:`.open` refers to codecs.open().

A similar heuristic is used to determine whether the name is an attribute of the currently documented class.

Also, if the name is prefixed with a dot, and no exact match is found, the target is taken as a suffix and all object names with that suffix are searched. For example, :py:meth:`.TarFile.close` references the tarfile.TarFile.close() function, even if the current module is not tarfile. Since this can get ambiguous, if there is more than one possible match, you will get a warning from Sphinx.

Note that you can combine the ~ and . prefixes: :py:meth:`~.TarFile.close` will reference the tarfile.TarFile.close() method, but the visible link caption will only be close().

The C Domain

The C domain (name c) is suited for documentation of C API.

.. c:function:: type name(signature)
Describes a C function. The signature should be given as in C, e.g.:

.. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)

This is also used to describe function-like preprocessor macros. The names of the arguments should be given so they may be used in the description.

Note that you don’t have to backslash-escape asterisks in the signature, as it is not parsed by the reST inliner.

.. c:member:: type name
Describes a C struct member. Example signature:

.. c:member:: PyObject* PyTypeObject.tp_bases

The text of the description should include the range of values allowed, how the value should be interpreted, and whether the value can be changed. References to structure members in text should use the member role.

.. c:macro:: name
Describes a “simple” C macro. Simple macros are macros which are used for code expansion, but which do not take arguments so cannot be described as functions. This is not to be used for simple constant definitions. Examples of its use in the Python documentation include PyObject_HEAD and Py_BEGIN_ALLOW_THREADS.

.. c:type:: name
Describes a C type (whether defined by a typedef or struct). The signature should just be the type name.

.. c:var:: type name
Describes a global C variable. The signature should include the type, such as:

.. c:var:: PyObject* PyClass_Type

Cross-referencing C constructs

The following roles create cross-references to C-language constructs if they are defined in the documentation:

:c:data:
Reference a C-language variable.

:c:func:
Reference a C-language function. Should include trailing parentheses.

:c:macro:
Reference a “simple” C macro, as defined above.

:c:type:
Reference a C-language type.

The C++ Domain

The C++ domain (name cpp) supports documenting C++ projects.

The following directives are available:

.. cpp:class:: signatures
.. cpp:function:: signatures
.. cpp:member:: signatures
.. cpp:type:: signatures
Describe a C++ object. Full signature specification is supported – give the signature as you would in the declaration. Here some examples:

.. cpp:function:: bool namespaced::theclass::method(int arg1, std::string arg2)

   Describes a method with parameters and types.

.. cpp:function:: bool namespaced::theclass::method(arg1, arg2)

   Describes a method without types.

.. cpp:function:: const T &array<T>::operator[]() const

   Describes the constant indexing operator of a templated array.

.. cpp:function:: operator bool() const

   Describe a casting operator here.

.. cpp:member:: std::string theclass::name

.. cpp:type:: theclass::const_iterator

Will be rendered like this:

bool namespaced::theclass::method(int arg1, std::string arg2)
Describes a method with parameters and types.

bool namespaced::theclass::method(arg1 None, arg2 None)
Describes a method without types.

const T& array<T>::operator[]() const
Describes the constant indexing operator of a templated array.

operator bool() const
Describe a casting operator here.

std::string theclass::name
type theclass::const_iterator
.. cpp:namespace:: namespace
Select the current C++ namespace for the following objects.

These roles link to the given object types:

:cpp:class:
:cpp:func:
:cpp:member:
:cpp:type:
Reference a C++ object. You can give the full signature (and need to, for overloaded functions.)

Nota

Sphinx’ syntax to give references a custom title can interfere with linking to template classes, if nothing follows the closing angle bracket, i.e. if the link looks like this: :cpp:class:`MyClass<T>`. This is interpreted as a link to T with a title of MyClass. In this case, please escape the opening angle bracket with a backslash, like this: :cpp:class:`MyClass\<T>`.

Note on References

It is currently impossible to link to a specific version of an overloaded method. Currently the C++ domain is the first domain that has basic support for overloaded methods and until there is more data for comparison we don’t want to select a bad syntax to reference a specific overload. Currently Sphinx will link to the first overloaded version of the method / function.

The Standard Domain

The so-called “standard” domain collects all markup that doesn’t warrant a domain of its own. Its directives and roles are not prefixed with a domain name.

The standard domain is also where custom object descriptions, added using the add_object_type() API, are placed.

There is a set of directives allowing documenting command-line programs:

.. option:: name args, name args, ...
Describes a command line option or switch. Option argument names should be enclosed in angle brackets. Example:

.. option:: -m <module>, --module <module>

   Run a module as a script.

The directive will create a cross-reference target named after the first option, referencable by option (in the example case, you’d use something like :option:`-m`).

.. envvar:: name
Describes an environment variable that the documented code or program uses or defines. Referencable by envvar.

.. program:: name
Like py:currentmodule, this directive produces no output. Instead, it serves to notify Sphinx that all following option directives document options for the program called name.

If you use program, you have to qualify the references in your option roles by the program name, so if you have the following situation

.. program:: rm

.. option:: -r

   Work recursively.

.. program:: svn

.. option:: -r revision

   Specify the revision to work upon.

then :option:`rm -r` would refer to the first option, while :option:`svn -r` would refer to the second one.

The program name may contain spaces (in case you want to document subcommands like svn add and svn commit separately).

Novo na versão 0.5.

There is also a very generic object description directive, which is not tied to any domain:

.. describe:: text
.. object:: text
This directive produces the same formatting as the specific ones provided by domains, but does not create index entries or cross-referencing targets. Example:

.. describe:: PAPER

   You can set this variable to select a paper size.

The JavaScript Domain

The JavaScript domain (name js) provides the following directives:

.. js:function:: name(signature)
Describes a JavaScript function or method. If you want to describe arguments as optional use square brackets as documented for Python signatures.

You can use fields to give more details about arguments and their expected types, errors which may be thrown by the function, and the value being returned:

.. js:function:: $.getJSON(href, callback[, errback])

   :param string href: An URI to the location of the resource.
   :param callback: Get's called with the object.
   :param errback:
       Get's called in case the request fails. And a lot of other
       text so we need multiple lines
   :throws SomeError: For whatever reason in that case.
   :returns: Something

This is rendered as:

$.getJSON(href, callback[, errback])
Parâmetros:
  • href (string) – An URI to the location of the resource.
  • callback – Get’s called with the object.
  • errback – Get’s called in case the request fails. And a lot of other text so we need multiple lines.
Gera SomeError: For whatever reason in that case.
Retorna: Something
.. js:class:: name
Describes a constructor that creates an object. This is basically like a function but will show up with a class prefix:

.. js:class:: MyAnimal(name[, age])

   :param string name: The name of the animal
   :param number age: an optional age for the animal

This is rendered as:

class MyAnimal(name[, age])
Parâmetros:
  • name (string) – The name of the animal
  • age (number) – an optional age for the animal
.. js:data:: name
Describes a global variable or constant.

.. js:attribute:: object.name
Describes the attribute name of object.

These roles are provided to refer to the described objects:

:js:func:
:js:class:
:js:data:
:js:attr:

The reStructuredText domain

The reStructuredText domain (name rst) provides the following directives:

.. rst:directive:: name
Describes a reST directive. The name can be a single directive name or actual directive syntax (.. prefix and :: suffix) with arguments that will be rendered differently. For example:

.. rst:directive:: foo

   Foo description.

.. rst:directive:: .. bar:: baz

   Bar description.

will be rendered as:

.. foo::
Foo description.

.. bar:: baz
Bar description.

.. rst:role:: name
Describes a reST role. For example:

.. rst:role:: foo

   Foo description.

will be rendered as:

:foo:
Foo description.

These roles are provided to refer to the described objects:

:rst:dir:
:rst:role:

More domains

The sphinx-contrib repository contains more domains available as extensions; currently a Ruby and an Erlang domain.

Anúncios

Comentários»

No comments yet — be the first.

Deixe uma resposta

Faça o login usando um destes métodos para comentar:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s

%d blogueiros gostam disto: