Skip to content

Instantly share code, notes, and snippets.

@jesugmz
Last active June 23, 2024 16:33
Show Gist options
  • Save jesugmz/d83b5e9de7ccc16f71c02adf7d2f3f44 to your computer and use it in GitHub Desktop.
Save jesugmz/d83b5e9de7ccc16f71c02adf7d2f3f44 to your computer and use it in GitHub Desktop.
Python docstring reStructuredText style

Python docstring reStructuredText style

Python Signatures

Signatures of functions, methods and class constructors can be given like they would be written in Python.

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='file') -> ast object

For functions with optional parameters that don't have default values (typically functions implemented in C extension modules without keyword argument support), you can use brackets to specify the optional parts:

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

It is customary to put the opening bracket before the comma.

Info field lists

.. versionadded:: 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. Creates a link if possible.
  • raises, raise, except, exception: That (and when) a specific exception is raised.
  • var, ivar, cvar: Description of a variable.
  • vartype: Type of a variable. Creates a link if possible.
  • returns, return: Description of the return value.
  • rtype: Return type. Creates a link if possible.

Note

In current release, all var, ivar and cvar are represented as "Variable". There is no difference at all.

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:: send_message(sender, recipient, message_body, [priority=1])

   Send a message to a recipient

   :param str sender: The person sending the message
   :param str recipient: The recipient of the message
   :param str message_body: The body of the message
   :param priority: The priority of the message, can be a number 1-5
   :type priority: integer or None
   :return: the message id
   :rtype: int
   :raises ValueError: if the message_body exceeds 160 characters
   :raises TypeError: if the message_body is not a basestring

This will render like this:

.. py:function:: send_message(sender, recipient, message_body, [priority=1])
   :noindex:

   Send a message to a recipient

   :param str sender: The person sending the message
   :param str recipient: The recipient of the message
   :param str message_body: The body of the message
   :param priority: The priority of the message, can be a number 1-5
   :type priority: integer or None
   :return: the message id
   :rtype: int
   :raises ValueError: if the message_body exceeds 160 characters
   :raises TypeError: if the message_body is not a basestring

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

:param int priority: The priority of the message, can be a number 1-5
.. versionadded:: 1.5

Container types such as lists and dictionaries can be linked automatically using the following syntax:

:type priorities: list(int)
:type priorities: list[int]
:type mapping: dict(str, int)
:type mapping: dict[str, int]
:type point: tuple(float, float)
:type point: tuple[float, float]

Multiple types in a type field will be linked automatically if separated by the word "or":

:type an_arg: int or None
:vartype a_var: str or int
:rtype: float or str

Cross-referencing Python objects

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

.. rst:role:: py:mod

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

.. rst:role:: 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 :confval:`add_function_parentheses` config
   value is ``True`` (the default).

.. rst:role:: py:data

   Reference a module-level variable.

.. rst:role:: py:const

   Reference a "defined" constant.  This may be a Python variable that is not
   intended to be changed.

.. rst:role:: py:class

   Reference a class; a dotted name may be used.

.. rst:role:: 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.

.. rst:role:: py:attr

   Reference a data attribute of an object.

.. rst:role:: py:exc

   Reference an exception.  A dotted name may be used.

.. rst:role:: py:obj

   Reference an object of unspecified type.  Useful e.g. as the
   :confval:`default_role`.

   .. versionadded:: 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 :mod:`codecs` module, ``:py:func:`open` `` always refers to the built-in function, while ``:py:func:`.open` `` refers to :func:`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().

@jesugmz
Copy link
Author

jesugmz commented Feb 11, 2018

@pythonian23
Copy link

The rendered parts don't seem to be rendered

@dupuyarc
Copy link

The problem appears to be that GitHub's reST formatter handles runs of three backquotes differently than Sphinx::

    ``:py:func:`filter```
    ...
    ``:py:func:`foo.filter```

GitHub parses the first set of three not as a backquote followed by double-backquote, but as a double-backquote followed by a backquote. That single backquote then splits the first backquote in the second function reference, and then the second triple-backquote starts another monospace run.

Adding spaces to split the triple backquotes correctly would solve this problem.

@jesugmz
Copy link
Author

jesugmz commented Apr 23, 2024

Solved by adding a space as escape character ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment