Sphinx – Sphinx

Sphinx inline markup

sphinx reference: Inline markup

Sphinx inline markup is down through interpreted text roles; they are written :rolename:`content`..

There are three types of roles:

Location cross references

sphinx ref: Cross-referencing arbitrary locations and sphinx role: ref.

We use:

:ref:`displayed text <label>`

To reference label defined in any document of the project. It allows linking across files, while the rest way is limited to a location in the same file.

If the label definition is followed by a section title then displayed text can be omitted and will be replaced by the section title.

E.g. the ReST – reStructuredText Internal document reference section is preceded with .. _internal:, so we have:

:ref:`internal` Internal document reference.
:ref:`That section <internal>` That section

We can also use as reference target a name option like

:ref:`see this topic <mytopic>` see this topic

See also Difference between ReST and Sphinx location reference in the ReST chapter.

Automatic labels for sections

Sphinx as an extension autosectionlabel that allow to reference each section by its title. Its is similar to Implicit Hyperlink Targets, but works across document.

In the doc:ReST chapter <ReST> we have used an Implicit Hyperlink Targets with:

`Transition`_
`how to draw an horizontal line <Transition>`_

we cannot use in the present chapter this ReST way of referencing a target because ReST processor know only one document. but we can use it with the autosectionlabel extension with

| The section :ref:`Transition` show
| :ref:`how to draw an horizontal line <Transition>`
| in your document.
The section Transition show
in your document.

Once you use the autosectionlabel extension new in version 1.4 Sphinx will detect duplicate labels, in contrast with Implicit Hyperlink Targets autolabel define a new label for each section, so if you have manually put a label before a section title which is identical to the title, it will be detected as duplicate.

These duplicate are harmless since they reference the same point. But some title in many document can be identical, you can have many introduction or conclusion in different parts. The duplicate may be problematic as any one can be matched by a reference. To disembiguate the labels there is an configuration option beginning version 1.6 autosectionlabel_prefix_document which prefix the automatic labels with with the name of the document it is in, followed by a colon.

With this setting instead of :ref:`Transition` you have to use :ref:`ReST:Transition` it avoid a potential ambiguity with a Transition paragraph in an other document, and has the additional benefit to avoid also all ambiguities with explicit labels in your documents.

Cross-referencing documents.

sphinx ref: Cross-referencing documents

In Sphinx it is possible to reference a document as follows

:doc:`ReST` ReST – reStructuredText

Extra cross-reference roles

Many are described in the sphinx ref:Cross-referencing other items of interest.

To reference a Python Enhancement Proposal use :pep:, for a Request for Comments :rfc:

Sphinx Roles.

The Sphinx roles are described in Sphinx: Inline markup and in the specific domains, e.g. python roles.

Some common markup are:

:abbr:`RFC(request for comments)` RFC
:file:`/etc/profile` /etc/profile
:manpage:`ls(1)` ls(1)
:regexp:`^[a-z]*.[0-9]` ^[a-z]*.[0-9]
:samp:`cp {file} {target}` cp file target

Python Roles.

role reference
:py:mod: module
:py:func: function
:py:data: module-level variable.
:py:const: constant
:py:class: class [1]
:py:meth: method [1] [2]
:py:attr: data attribute of an object
:py:exc: exception [1]
[1](1, 2, 3) Class, methods, exceptions may be dotted names.
[2]The role text should include the type name and the method name

You may supply an explicit title and reference target: :role:`title <target>`.

Sphinx directives

Sphinx includes its own directives, which are not available in the docutils builders.

Table of contents.

.. toctree::
   :maxdepth: ‹depth›
   :glob:

   ‹file 1 without file name extension›
   ‹file 2 without file name extension›

The toctree directive create a table of contents across files.

A glob option enables to use wildcards in the filenames, e.g. /comp/* means all files under the directory comp.

Relative names are relative to the document the directive occurs in, absolute names are relative to the source directory.

The depth can be further restricted per file by inserting the following Field list type element in the very first line of the file:

:tocdepth: ‹depth›

See Sphinx: Toc tree for other options.

To get a table of content inside a file, use the reST table of contents

Index.

Entries in the index are created automatically from all information units like functions, classes or attributes but those with a :noindex: option. Explicit manual entries are made as:

.. index:: ‹entry 1›, ‹entry 2›, !<entry 3> ...
   single: ‹entry›; ‹sub-entry›
   pair: ‹1st part›; ‹2nd part›
   triple:  ‹1st part›; ‹2nd part›; <3rd part>

The first two versions create single (sub-)entries, while pair creates two entries “‹1st part›; ‹2nd part›” and “‹2nd part›; <1st part›”; and triple makes three entries.

With the exclamation mark, the <entry 3> is the main entry for this term and is put in bold.

You can also use the keywords see and seealso with see: foo bar or seealso: bar foo.

Glossary.

A glossary is a Definition list:

.. glossary::
   :sorted:

   name1
   name2
      definition of both name1 and name2

Note, Warning, Seealso.

They are paragraph-level markups

Note

This is a note.

Warning

This is a warning.

See also

Apples
A kind of fruit.

Selective inclusion.

A block may be included depending of the presence of some tag (Sphinx ref):

..only:: <expression>

The expression is made of tags combined in boolean expressions like html and draft.

The format and the name of the current builder is set as predefined tag, if needed it can be prefixed to differentiate format and builer, like format_html or builder_html

You can define tags via the -t command-line option of sphinx-build.

In the configuration file you can use tags.has('tag') to query, tags.add('tag') and tags.remove('tag') to change.

An alternative is the ifconfig directive (Sphinx ref) from the sphinx.ext.ifconfig extension:

.. ifconfig:: <Python expression>

To evaluate the expression all variables registered from conf.py are availables, to add a config value use the setup function in conf.py:

def setup(app):
 app.add_config_value('newconf', 'default', True)

the third parameter should always be True.

Defining a css class for some part.

There is at least three ways of doing it:

.. role:: red

An example of :red:`red text`.

.. container:: red

   Here the full block is red.

An undecorated paragraph.

.. class:: red

This paragraph too is is red.

.. admonition:: Big warning
   :class: red

   Big warning text is red.

After applying rst2html you get:

<p>An example of <span class="red">red text</span>.</p>
<div class="red container">
Here the full block of test is red.</div>
<p>An undecorated paragraph.</p>
<p class="red">This paragraph too is is red.</p>
<div class="red admonition">
<p class="first admonition-title">Big warning</p>
<p class="last">Big warning text is red.</p>

Here I have taken the admonition directive as example but any directive that allow the :class: option would do.

As it generates a span the role directive is the only one that allow to apply your style to a part of a paragraph.

The class works as expected with rest2html, but directive fail with Sphinx. You have to replace it with

.. rst-class:: red

This paragraph too is is red.

Sphinx use rst-class to replace the ReSt class directive that is shadowed by Sphinx. This is only stated in a small footnote of Sphinx reSt Primer.

Using your new style

To use your new class you need a css style like:

.red {
  color: red;
}

You put it in a stylesheet, to give it’s location:

  • With rst2html you must specify the stylesheet’s location with a --stylesheet (for a URL) or --stylesheet-path for a local file.

  • With Sphinx a flexible solution is to add your own css file in the _static directory and give its location with a template that you put in the _template directory. You can use a file layout.html wich extend the original template of the same name:

    {% extends "!layout.html" %}
    {% set css_files = css_files + ["_static/style.css"] %}
    

    For more details refer to Sphinx: Templating.

Sphinx Source Code.

Code highlighting.

Sphinx ref: showing code

The code blocks are highlighted by sphinx, there is a default language of Python that can be changed in the configuration, by setting the configuration option highlight_language.

The default Highlighting language used by Pygment in Literal Blocks is set for following snippets of code examples by:

.. highlight:: ‹language›
   :linenothreshold: ‹number›

The option language may be any language supported by a Pygment lexer.

The additional linenothreshold option switches on line numbering for blocks of size beyond ‹number› lines.

When using Sphinx you can specify the highlighting in a single literal block:

.. code-block:: ‹language›
   :linenos:

   ‹body›

The linenos option switches on line numbering. You can also use some options that are described for the Source code include., namely linenos, lineno-start, caption, name, dedent.

When using base ReST parser use instead code keyword.

Source code include.

Source code is included in Sphinx with the directive literalinclude.

To include the source file example.py as a literal block use:

.. literalinclude:: code/example.py
   :linenos:
1
print("Hello {0}!".format("World"))

There are more options:

.. literalinclude:: code/example.py
   :caption: Example of code
   :name: example.py
   :language: python
   :dedent: 4
   :linenos:
   :lines: 1,3,5-10,20-
   :emphasize-line: 4,5

caption is the displayed title before the block, name is the reST name option used as an internal reference target.

dedent strip left whitespaces, linenos add a line numbering alternatively lineno-start begin the numbering at the given number.

The options language and linenos set the highlighting to ‹language› and enables line numbers respectively.

You can select lines by the lines option or by start-after: <string> and/or end-before: <string> (<string>s are not quoted).

Whe emphasize the fourth and fifth selected line, which in the above example are the lines 5 and 10 of the source.

If it is a Python module, instead of selecting by lines you can select a a class function or method to include by using the option pyobject:

.. literalinclude:: code/example.py
   :pyobject: MyClass.some_method

For including a ReST source file use the rest directive include.

Source code directives.

There are very powerful directives in Sphinx for documenting source code, each programming langage has a specific domains .

The following markups are related to documenting python source code.

.. module:: name Marks the beginning of the description of a module
.. currentmodule:: name The classes, functions etc. documented from here are in the given module
.. exception:: name[(signature)] Describes an exception class.
.. class:: name[(signature)] Describes a class. [3]
.. attribute:: name Describes an object data attribute.
.. method:: name(signature) Describes an object method.
.. staticmethod:: name(signature) Describes a static method.
.. classmethod:: name(signature) Describes a class method.
.. decorator:: name(signature) Describes a class method.
.. classmethod:: name(signature) Describes a class method.
[3]Methods and attributes belonging to the class should be placed in this directive’s body.
[4]

Signatures of functions, methods, class constructors, decorators can be given like in Python, but with optional parameters indicated by brackets:

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

autodoc

There is an autodoc version of the source code directives which include documentation from docstrings:

  • automodule, autoclass, autoexception. Document a module, class or exception. They insert the docstring of the object itself; if you add a :members: option followed by a specific list of members, they will be included in the documentation. An empty list of members includes all members.

    .. autoclass:: Noodle
       :members: eat, slurp
    
  • autofunction, autodata, automethod, autoattribute

    are used to document the respective type of object. autodata and autoattribute support an annotation option taht will show not only the name but the representation of the object.

Using info field lists in Docstrings.

Inside Python object description directives the following fields are recognized: param, arg, key, type, raises, raise, except, exception, var, ivar, cvar, returns, return, rtype.

Sphinx.divide(i, j)

divide two numbers

Parameters:
  • i (int) – numerator
  • j – denominator
Returns:

quotient

Return type:

integer

Raises:

ZeroDivisionError

def divide(self, i, j):
    """Divide two numbers.

    This function is to show how the docstring look, using pure Sphinx syntax,
    with explicit fields.

    :param i: numerator
    :type i: int
    :param j: denominator
    :type j: int
    :return: quotient
    :rtype: integer
    :raises: :exc:`ZeroDivisionError`
"""
code.divide.divide(self, i, j)

Divide two numbers.

This function is to show how the docstring look, using pure Sphinx syntax, with explicit fields.

Parameters:
  • i (int) – numerator
  • j (int) – denominator
Returns:

quotient

Return type:

integer

Raises:

ZeroDivisionError

Docstring alternate syntax.

For docstrings you can use the previous fields or the alternate syntax that is recommended by Openalea Project. :

def example(arg1, arg2):
    """Docstring example.

    :Parameters:
      - `arg1` (float) - the first value
      - `arg2` (float) - the second value

    :Returns:
        arg1/arg2

    :Returns Type:
        float

    :Examples:

    >>> import template
    >>> a = MainClass()
    >>> a.example(6,2)
    1.5

    .. note:: can be useful to emphasize
       important features.
    .. seealso:: :py:exc:`ZeroDivisionError`
    .. warning:: arg2 must be non-zero.
    .. todo:: check that arg2 is non zero.
"""
code.docstring.example(arg1, arg2)

Docstring example.

Parameters:
  • arg1 (float) - the first value
  • arg2 (float) - the second value
Returns:

arg1/arg2

Returns Type:

float

Examples:
>>> import template
>>> a = MainClass()
>>> a.example(6,2)
1.5

Note

can be useful to emphasize important features.

Warning

arg2 must be non-zero.

Todo

check that arg2 is non zero.

Google style docstrings.

Using Restructured texts in your python code, is quite cumbersome, it produces an easily readable documentation, but cryptic source code.

If we want to follow the style of PEP257 we can use the Google Python style guide also recommended by the Khan Academy Style Guide.

NumPy style guide Alternatively there is a NumPy/SciPy style of documentation.

But they produces docstrings that are not recognized by Sphinx, and not decorated in html output.

The extension napoleon preprocess NumPy and Google style docstrings and converts them to reStructuredText before Sphinx parse the source code. You need to configure it in your conf.py file.

def example(arg1, arg2):
    """Division of two reals.

    This function is only to show how we can format docstrings using
    Google Style Guide.

    Args:
        - arg1 (float): The first value.
        - arg2 (float): The second value, cannot be Nul.

    Returns:
        float: Division arg1/arg2.

    Raises:
        ZeroDivisionError: if arg2 is zero.

    Example:
        >>> import template
        >>> a = MainClass()
        >>> a.example(6,2)
        1.5

    Todo:
        Check that arg2 is non zero, and throw an exception.
"""
code.gstyle_docstring.example(arg1, arg2)

Division of two reals.

This function is only to show how we can format docstrings using Google Style Guide.

Args:
  • arg1 (float): The first value.
  • arg2 (float): The second value, cannot be Nul.
Returns:
float: Division arg1/arg2.
Raises:
ZeroDivisionError: if arg2 is zero.
Example:
>>> import template
>>> a = MainClass()
>>> a.example(6,2)
1.5
Todo:
Check that arg2 is non zero, and throw an exception.

Look here for a larger example.

How napoleon transform my docstrings.

We may be curious to know what exactly napoleon generates. It can allow us to fix error in the output by changing our docstring or adding Sphinx fields.

We can call napoleon from python to learn what it generates:

>>> docstring="""
... Division of two reals.
...
..."""
>>> from sphinx.ext.napoleon import Config
>>> from sphinx.ext.napoleon.docstring import GoogleDocstring
>>> config = Config(napoleon_use_param=True, napoleon_use_rtype=True)
>>> print(GoogleDocstring(docstring), config)

And we have the decorated result:

Division of two reals.

This function is only to show how we can format docstrings using
Google Style Guide.

:param - arg1: The first value.
:type - arg1: float
:param - arg2: The second value, cannot be Nul.
:type - arg2: float

:returns: Division arg1/arg2.
:rtype: float

:raises: :exc:`ZeroDivisionError` -- if arg2 is zero.

.. rubric:: Example

>>> import template
>>> a = MainClass()
>>> a.example(6,2)
1.5

.. todo:: Check that arg2 is non zero, and throw an exception.

If you want to experiment with output of napoleon you can look at the parameters of GoogleDocstring in the source code