The Python Domain¶
Added in version 1.0.
The Python domain (namepy) provides the following directives for moduledeclarations:
- ..py:module::name¶
This directive marks the beginning of the description of a module (or packagesubmodule, in which case the name should be fully qualified, including thepackage name). A description of the module such as the docstring can beplaced 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(commaseparatedlist)¶
Indicate platforms which the module is available (if it is available onall platforms, the option should be omitted). The keys are shortidentifiers; examples that are in use include “IRIX”, “Mac”, “Windows”and “Unix”. It is important to use a key which has already been used whenapplicable.
- :synopsis:purpose(text)¶
Consist of one sentence describing the module’s purpose – it is currentlyonly used in the Global Module Index.
- :deprecated:(noargument)¶
Mark a module as deprecated; it will be designated as such in variouslocations then.
- ..py:currentmodule::name¶
This directive tells Sphinx that the classes, functions etc. documented fromhere are in the given module (like
py:module), but it will notcreate index entries, an entry in the Global Module Index, or a link targetforpy:mod. This is helpful in situations where documentationfor things in a module is spread over multiple files or sections – onelocation has thepy:moduledirective, the others onlypy:currentmodule.
The following directives are provided for module and class contents:
- ..py:function::name(parameters)¶
- ..py:function::name[typeparameters](parameters)
Describes a module-level function.The signature should include the parameters,together with optional type parameters,as given in the Python function definition, seePython 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 requiredand how they are used (especially whether mutable objects passed asparameters are modified), side effects, and possible exceptions.
This information can (in any
pydirective) optionally be given in astructured form, seeInfo field lists.options
- :async:(novalue)¶
Indicate the function is an async function.
Added in version 2.1.
- :canonical:(fullqualifiednameincludingmodulename)¶
Describe the location where the object is defined if the object isimported from other modules
Added in version 4.0.
- :single-line-parameter-list:(novalue)¶
Ensures that the function’s arguments will be emitted on a single logicalline, overriding
python_maximum_signature_line_lengthandmaximum_signature_line_length.Added in version 7.1.
- :single-line-type-parameter-list:(novalue)¶
Ensure that the function’s type parameters are emitted on a singlelogical line, overriding
python_maximum_signature_line_lengthandmaximum_signature_line_length.Added in version 7.1.
- ..py:data::name¶
Describes global data in a module, including both variables and values usedas “defined constants.”Consider using
py:typefor type aliases insteadandpy:attributefor class variables and instance attributes.options
- :type:typeofthevariable(text)¶
This will be parsed as a Python expression for cross-referencingthe type annotation.As such, the argument to
:type:should be a validannotation expression.Caution
The valid syntax for the
:type:directive option differs fromthe syntax for the:type:info field.The:type:directive option does not understandreStructuredText markup or theororofkeywords,meaning unions must use|and sequences must use square brackets,and roles such as:ref:`...`cannot be used.Added in version 2.4.
- :value:initialvalueofthevariable(text)¶
Added in version 2.4.
- :canonical:(fullqualifiednameincludingmodulename)¶
Describe the location where the object is defined if the object isimported from other modules
Added in version 4.0.
- ..py:exception::name¶
- ..py:exception::name(parameters)
- ..py:exception::name[typeparameters](parameters)
Describes an exception class.The signature can, but need not include parentheses with constructor arguments,or may optionally include type parameters (seePEP 695).
options
- :final:(novalue)¶
Indicate the class is a final class.
Added in version 3.1.
- :single-line-parameter-list:(novalue)¶
See
py:class:single-line-parameter-list.Added in version 7.1.
- :single-line-type-parameter-list:(novalue)¶
See
py:class:single-line-type-parameter-list.Added in version 7.1.
- ..py:class::name¶
- ..py:class::name(parameters)
- ..py:class::name[typeparameters](parameters)
Describes a class.The signature can optionally include type parameters (seePEP 695)or parentheses with parameters which will be shown as the constructor arguments.See alsoPython Signatures.
Methods and attributes belonging to the class should be placed in thisdirective’s body. If they are placed outside, the supplied name shouldcontain 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
- :abstract:(novalue)¶
Indicate that the class is an abstract base class.This produces the following output:
- abstractclassCheese
A cheesy representation.
Added in version 8.2.
- :canonical:(fullqualifiednameincludingmodulename)¶
Describe the location where the object is defined if the object isimported from other modules
Added in version 4.0.
- :final:(novalue)¶
Indicate the class is a final class.
Added in version 3.1.
- :single-line-parameter-list:(novalue)¶
Ensures that the class constructor’s arguments will be emitted on a singlelogical line, overriding
python_maximum_signature_line_lengthandmaximum_signature_line_length.Added in version 7.1.
- :single-line-type-parameter-list:(novalue)¶
Ensure that the class type parameters are emitted on a single logicalline, overriding
python_maximum_signature_line_lengthandmaximum_signature_line_length.
- ..py:attribute::name¶
Describes an object data attribute. The description should includeinformation about the type of the data to be expected and whether it may bechanged directly.Type aliases should be documented with
py:type.options
- :type:typeoftheattribute(text)¶
This will be parsed as a Python expression for cross-referencingthe type annotation.As such, the argument to
:type:should be a validannotation expression.Caution
The valid syntax for the
:type:directive option differs fromthe syntax for the:type:info field.The:type:directive option does not understandreStructuredText markup or theororofkeywords,meaning unions must use|and sequences must use square brackets,and roles such as:ref:`...`cannot be used.Added in version 2.4.
- :value:initialvalueoftheattribute(text)¶
Added in version 2.4.
- :canonical:(fullqualifiednameincludingmodulename)¶
Describe the location where the object is defined if the object isimported from other modules
Added in version 4.0.
- ..py:property::name¶
Describes an object property.
Added in version 4.0.
options
- :abstract:(novalue)¶
- :abstractmethod:(novalue)¶
Indicate the property is abstract.This produces the following output:
- abstractpropertyCheese.amount_in_stock
Cheese levels at theNational Cheese Emporium.
Changed in version 8.2:The
:abstract:alias is also supported.
- :classmethod:(novalue)¶
Indicate the property is a classmethod.
Added in version 4.2.
- :type:typeoftheproperty(text)¶
This will be parsed as a Python expression for cross-referencingthe type annotation.As such, the argument to
:type:should be a validannotation expression.Caution
The valid syntax for the
:type:directive option differs fromthe syntax for the:type:info field.The:type:directive option does not understandreStructuredText markup or theororofkeywords,meaning unions must use|and sequences must use square brackets,and roles such as:ref:`...`cannot be used.
- ..py:type::name¶
Describe atype alias.
The type that the alias represents should be describedwith the
canonicaloption.This directive supports an optional description body.For example:
..py:type:: UInt64 Represent a 64-bit positive integer.
will be rendered as follows:
- typeUInt64¶
Represent a 64-bit positive integer.
options
- :canonical:(text)¶
The canonical type represented by this alias, for example:
..py:type:: StrPattern:canonical: str | re.Pattern[str] Represent a regular expression or a compiled pattern.
This is rendered as:
- typeStrPattern=str|re.Pattern[str]¶
Represent a regular expression or a compiled pattern.
Added in version 7.4.
- ..py:method::name(parameters)¶
- ..py:method::name[typeparameters](parameters)
Describes an object method. The parameters should not include the
selfparameter. The description should include similar information to thatdescribed forfunction. See alsoPython Signatures andInfo field lists.options
- :abstract:(novalue)¶
- :abstractmethod:(novalue)¶
Indicate the method is an abstract method.This produces the following output:
- abstractmethodCheese.order_more_stock()
Order more cheese (we’re fresh out!).
Added in version 2.1.
Changed in version 8.2:The
:abstract:alias is also supported.
- :async:(novalue)¶
Indicate the method is an async method.
Added in version 2.1.
- :canonical:(fullqualifiednameincludingmodulename)¶
Describe the location where the object is defined if the object isimported from other modules
Added in version 4.0.
- :classmethod:(novalue)¶
Indicate the method is a class method.
Added in version 2.1.
- :final:(novalue)¶
Indicate the method is a final method.
Added in version 3.1.
- :single-line-parameter-list:(novalue)¶
Ensures that the method’s arguments will be emitted on a single logicalline, overriding
python_maximum_signature_line_lengthandmaximum_signature_line_length.Added in version 7.1.
- :single-line-type-parameter-list:(novalue)¶
Ensure that the method’s type parameters are emitted on a single logicalline, overriding
python_maximum_signature_line_lengthandmaximum_signature_line_length.Added in version 7.2.
- :staticmethod:(novalue)¶
Indicate the method is a static method.
Added in version 2.1.
- ..py:staticmethod::name(parameters)¶
- ..py:staticmethod::name[typeparameters](parameters)
Like
py:method, but indicates that the method is a static method.Added in version 0.4.
- ..py:classmethod::name(parameters)¶
- ..py:classmethod::name[typeparameters](parameters)
Like
py:method, but indicates that the method is a class method.Added in version 0.6.
- ..py:decorator::name¶
- ..py:decorator::name(parameters)
- ..py:decorator::name[typeparameters](parameters)
Describes a decorator function. The signature should represent the usage asa decorator. For example, given the functions
defremovename(func):func.__name__=''returnfuncdefsetnewname(name):defdecorator(func):func.__name__=namereturnfuncreturndecorator
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).)Refer to a decorator function using the
py:decorole.- :single-line-parameter-list:(novalue)¶
Ensures that the decorator’s arguments will be emitted on a single logicalline, overriding
python_maximum_signature_line_lengthandmaximum_signature_line_length.Added in version 7.1.
- :single-line-type-parameter-list:(novalue)¶
Ensure that the decorator’s type parameters are emitted on a singlelogical line, overriding
python_maximum_signature_line_lengthandmaximum_signature_line_length.Added in version 7.2.
- ..py:decoratormethod::name¶
- ..py:decoratormethod::name(signature)
- ..py:decoratormethod::name[typeparameters](signature)
Same as
py:decorator, but for decorators that are methods.Refer to a decorator method using the
py:decorole.
Python Signatures¶
Signatures of functions, methods and class constructors can be given like theywould be written in Python.This can include default values, positional-only or keyword-only parameters,type annotations, and type parameters.For example:
..py:function:: compile(source: str, filename: Path, symbol: str = 'file') -> ast.AST
For functions with optional parameters that don’t have default values(typically functions implemented in C extension modules without keywordargument support),you can list multiple versions of the same signature in a single directive:
- compile(source)
- compile(source,filename)
- compile(source,filename,symbol)
Another approach is to use square brackets to specify the optional parts.When using square brackets, it is customary to placethe opening bracket before the comma ([,).
- compile(source[,filename[,symbol]])
Python 3.12 introducedtype parameters, which are type variablesdeclared directly within the class or function definition:
classAnimalList[AnimalT](list[AnimalT]):...defadd[T](a:T,b:T)->T:returna+b
The corresponding reStructuredText markup would be:
..py:class:: AnimalList[AnimalT]..py:function:: add[T](a: T, b: T) -> T
Info field lists¶
Added in version 0.4.
Changed in version 3.0:meta fields are added.
Inside Python object description directives,reStructuredText field lists with these fieldsare 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 specificexception 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 willnot be shown on output document. For example,:metaprivate:indicatesthe python object is private member. It is used insphinx.ext.autodocfor filtering members.
Note
In current release, allvar,ivar andcvar are represented as“Variable”. There is no difference at all.
The field names must consist of one of these keywords and an argument (exceptforreturns andrtype, which do not need an argument). This is bestexplained 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: int 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 asingle word, like this:
:param int priority: The priority of the message, can be a number 1-5Added in version 1.5.
Container types such as lists and dictionaries can be linked automaticallyusing 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 automaticallyif separated by either the vertical bar (|) or the word “or”:
:type an_arg: int or None:vartype a_var: str or int:rtype: float or str:type an_arg: int | None:vartype a_var: str | int:rtype: float | str
Cross-referencing Python objects¶
The following roles refer to objects in modules and are possibly hyperlinked ifa matching identifier is found:
- :py:mod:¶
Reference a module; a dotted name may be used. This should also be used forpackage names.
- :py:func:¶
Reference a Python function; dotted names may be used. The role text needsnot include trailing parentheses to enhance readability; they will be addedautomatically by Sphinx if the
add_function_parenthesesconfigvalue isTrue(the default).
- :py:deco:¶
Reference a Python decorator; dotted names may be used.The rendered output will be prepended with an at-sign (
@),for example::py:deco:`removename`produces@removename.
- :py:data:¶
Reference a module-level variable.
- :py:const:¶
Reference a “defined” constant. This may be a Python variable that is notintended 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 nameand the method name; if it occurs within the description of a type, the typename 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:type:¶
Reference a type alias.
- :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.Added in version 0.4.
Target specification¶
The target can be specified as a fully qualified name(e.g.:py:meth:`my_module.MyClass.my_method`)or any shortened version(e.g.:py:meth:`MyClass.my_method` or:py:meth:`my_method`).Seetarget resolution for details on the resolution of shortened names.
Cross-referencing modifiers can be applied.In short:
You may supply an explicit title and reference target:
:py:mod:`mathematicalfunctions<math>`will refer to themathmodule,but the link text will be “mathematical functions”.If you prefix the content with an exclamation mark (
!),no reference/hyperlink will be created.If you prefix the content with
~, the link text will only be the lastcomponent of the target.For example,:py:meth:`~queue.Queue.get`willrefer toqueue.Queue.getbut only displaygetas the link text.
Target resolution¶
A given link target name is resolved to an object using the following strategy:
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’scodecs module,:py:func:`open` always refers to the built-in function,while:py:func:`.open` refers tocodecs.open().
A similar heuristic is used to determine whether the name is an attribute ofthe currently documented class.
Also, if the name is prefixed with a dot, and no exact match is found, thetarget is taken as a suffix and all object names with that suffix are searched.For example,:py:meth:`.TarFile.close` references thetarfile.TarFile.close() function, even if the current module is nottarfile. Since this can get ambiguous, if there is more than one possiblematch, you will get a warning from Sphinx.
Note that you can combine the~ and. prefixes::py:meth:`~.TarFile.close` will reference thetarfile.TarFile.close()method, but the visible link caption will only beclose().