The Python Domain¶
New in version 1.0.
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). A description of the module such as the docstring can be placed in the body of the directive.
This directive will also cause an entry in the global module index.
Changed in version 5.2: Module directives support body content.
options
- :platform: platforms (comma separated list)¶
Indicate platforms 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.
- :synopsis: purpose (text)¶
Consist of one sentence describing the module’s purpose – it is currently only used in the Global Module Index.
- :deprecated: (no argument)¶
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 forpy:mod
. This is helpful in situations where documentation for things in a module is spread over multiple files or sections – one location has thepy:module
directive, the others onlypy:currentmodule
.
The following directives are provided for module and class contents:
- .. py:function:: name(parameters)¶
- .. py:function:: name[type parameters](parameters)
Describes a module-level function. The signature should include the parameters, together with optional type parameters, as given in the Python function definition, see Python Signatures. For example:
.. py:function:: Timer.repeat(repeat=3, number=1_000_000) .. py:function:: add[T](a: T, b: T) -> T
For methods you should use
py:method
.The description normally includes information about the parameters required and how they are used (especially whether mutable objects passed as parameters are modified), side effects, and possible exceptions.
This information can (in any
py
directive) optionally be given in a structured form, see Info field lists.options
- :async: (no value)¶
Indicate the function is an async function.
New in version 2.1.
- :canonical: (full qualified name including module name)¶
Describe the location where the object is defined if the object is imported from other modules
New in version 4.0.
- :single-line-parameter-list: (no value)¶
Ensures that the function’s arguments will be emitted on a single logical line, overriding
python_maximum_signature_line_length
andmaximum_signature_line_length
.New in version 7.1.
- :single-line-type-parameter-list: (no value)¶
Ensure that the function’s type parameters are emitted on a single logical line, overriding
python_maximum_signature_line_length
andmaximum_signature_line_length
.New in version 7.1.
- .. 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.
options
- :type: type of the variable (text)¶
New in version 2.4.
- :value: initial value of the variable (text)¶
New in version 2.4.
- :canonical: (full qualified name including module name)¶
Describe the location where the object is defined if the object is imported from other modules
New in version 4.0.
- .. py:exception:: name¶
- .. py:exception:: name(parameters)
- .. py:exception:: name[type parmeters](parameters)
Describes an exception class. The signature can, but need not include parentheses with constructor arguments, or may optionally include type parameters (see PEP 695).
options
- :final: (no value)¶
Indicate the class is a final class.
New in version 3.1.
- :single-line-parameter-list: (no value)¶
See
py:class:single-line-parameter-list
.New in version 7.1.
- :single-line-type-parameter-list: (no value)¶
See
py:class:single-line-type-parameter-list
.New in version 7.1.
- .. py:class:: name¶
- .. py:class:: name(parameters)
- .. py:class:: name[type parmeters](parameters)
Describes a class. The signature can optionally include type parameters (see PEP 695) or 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.
options
- :canonical: (full qualified name including module name)¶
Describe the location where the object is defined if the object is imported from other modules
New in version 4.0.
- :final: (no value)¶
Indicate the class is a final class.
New in version 3.1.
- :single-line-parameter-list: (no value)¶
Ensures that the class constructor’s arguments will be emitted on a single logical line, overriding
python_maximum_signature_line_length
andmaximum_signature_line_length
.New in version 7.1.
- :single-line-type-parameter-list: (no value)¶
Ensure that the class type parameters are emitted on a single logical line, overriding
python_maximum_signature_line_length
andmaximum_signature_line_length
.
- .. 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.
options
- :type: type of the attribute (text)¶
New in version 2.4.
- :value: initial value of the attribute (text)¶
New in version 2.4.
- :canonical: (full qualified name including module name)¶
Describe the location where the object is defined if the object is imported from other modules
New in version 4.0.
- .. py:property:: name¶
Describes an object property.
New in version 4.0.
options
- :abstractmethod: (no value)¶
Indicate the property is abstract.
- :classmethod: (no value)¶
Indicate the property is a classmethod.
New in version 4.2.
- :type: type of the property (text)¶
- .. py:method:: name(parameters)¶
- .. py:method:: name[type parameters](parameters)
Describes an object method. The parameters should not include the
self
parameter. The description should include similar information to that described forfunction
. See also Python Signatures and Info field lists.options
- :abstractmethod: (no value)¶
Indicate the method is an abstract method.
New in version 2.1.
- :async: (no value)¶
Indicate the method is an async method.
New in version 2.1.
- :canonical: (full qualified name including module name)¶
Describe the location where the object is defined if the object is imported from other modules
New in version 4.0.
- :classmethod: (no value)¶
Indicate the method is a class method.
New in version 2.1.
- :final: (no value)¶
Indicate the method is a final method.
New in version 3.1.
- :single-line-parameter-list: (no value)¶
Ensures that the method’s arguments will be emitted on a single logical line, overriding
python_maximum_signature_line_length
andmaximum_signature_line_length
.New in version 7.1.
- :single-line-type-parameter-list: (no value)¶
Ensure that the method’s type parameters are emitted on a single logical line, overriding
python_maximum_signature_line_length
andmaximum_signature_line_length
.New in version 7.2.
- :staticmethod: (no value)¶
Indicate the method is a static method.
New in version 2.1.
- .. py:staticmethod:: name(parameters)¶
- .. py:staticmethod:: name[type parameters](parameters)
Like
py:method
, but indicates that the method is a static method.New in version 0.4.
- .. py:classmethod:: name(parameters)¶
- .. py:classmethod:: name[type parameters](parameters)
Like
py:method
, but indicates that the method is a class method.New in version 0.6.
- .. py:decorator:: name¶
- .. py:decorator:: name(parameters)
- .. py:decorator:: name[type parameters](parameters)
Describes a decorator function. The signature should represent the usage as a decorator. For example, given the functions
def removename(func): func.__name__ = '' return func def setnewname(name): def decorator(func): func.__name__ = name return func return decorator
the descriptions should look like this:
.. py:decorator:: removename Remove name of the decorated function. .. py:decorator:: setnewname(name) Set name of the decorated function to *name*.
(as opposed to
.. py:decorator:: removename(func)
.)There is no
py:deco
role to link to a decorator that is marked up with this directive; rather, use thepy:func
role.- :single-line-parameter-list: (no value)¶
Ensures that the decorator’s arguments will be emitted on a single logical line, overriding
python_maximum_signature_line_length
andmaximum_signature_line_length
.New in version 7.1.
- :single-line-type-parameter-list: (no value)¶
Ensure that the decorator’s type parameters are emitted on a single logical line, overriding
python_maximum_signature_line_length
andmaximum_signature_line_length
.New in version 7.2.
- .. py:decoratormethod:: name¶
- .. py:decoratormethod:: name(signature)
- .. py:decoratormethod:: name[type parameters](signature)
Same as
py:decorator
, but for decorators that are methods.Refer to a decorator method using the
py:meth
role.
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:
- compile(source[, filename[, symbol]])¶
It is customary to put the opening bracket before the comma.
Python 3.12 introduced type parameters, which are type variables declared directly within the class or function definition:
class AnimalList[AnimalT](list[AnimalT]):
...
def add[T](a: T, b: T) -> T:
return a + b
The corresponding reStructuredText documentation would be:
.. py:class:: AnimalList[AnimalT]
.. py:function:: add[T](a: T, b: T) -> T
See PEP 695 and PEP 696 for details and the full specification.
Info field lists¶
New in version 0.4.
Changed in version 3.0: meta fields are added.
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.meta
: Add metadata to description of the python object. The metadata will not be shown on output document. For example,:meta private:
indicates the python object is private member. It is used insphinx.ext.autodoc
for filtering members.
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:
- send_message(sender, recipient, message_body[, priority=1])¶
Send a message to a recipient
- Parameters:
- Returns:
the message id
- Return type:
- Raises:
ValueError – if the message_body exceeds 160 characters
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
New in version 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:
- :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 isTrue
(the default).
- :py:data:¶
Reference a module-level variable.
- :py:const:¶
Reference a “defined” constant. This may be 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.
Note
The role is also able to refer to property.
- :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
.New in version 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()
.