Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark, in light modeAuto light/dark, in dark modeSkip to content
Python Developer's Guide
Logo
Python Developer's Guide
Back to top

reStructuredText markup

This document describes the custom reStructuredText markup introduced by Sphinxto support Python documentation and how it should be used.

Quick reference

This table summarizes which markup should be used for some commonly usedelements:

Element

Markup

See also

arguments/parameters

*arg*

Inline markup

variables/literals/code

``foo``,``42``,``len(s)-1``

Inline markup

True/False/None

``True``,``False``,``None``

Inline markup

function definitions

..function::print(*args)

Directives

function references

:func:`print`

Roles

attribute definitions

..attribute:`attr-name`

Information units

attribute references

:attr:`attr-name`

Roles

reference labels

.._label-name:

Cross-linking markup

internal references

:ref:`label-name`

Cross-linking markup

external links

`Linktext<https://example.com>`_

Hyperlinks

roles w/ custom text

:role:`customtext<target>`

Roles

roles w/ only last part

:role:`~hidden.hidden.visible`

Roles

roles w/o link

:role:`!target`

Roles

issues

:gh:`ID`,:issue:`ID`

Roles

CPython source

:source:`PATH`

Roles

comments

..acomment

Comments

reStructuredText primer

This section is a brief introduction to reStructuredText (reST) concepts andsyntax, intended to provide authors with enough information to author documentsproductively. Since reST was designed to be a simple, unobtrusive markuplanguage, this will not take too long.

See also

The authoritativereStructuredText UserDocumentation.

Use of whitespace

All reST files use an indentation of 3 spaces; no tabs are allowed. Themaximum line length is 80 characters for normal text, but tables, deeplyindented code samples and long links may extend beyond that. Code examplebodies should use normal Python 4-space indentation.

Make use of multiple blank lines where applicable to clarify the structure ofthe reST file. Extra blank lines help group sections together to make theorganization of the file clearer.

A sentence-ending period may be followed by one or two spaces. While reSTignores the second space, it is customarily put in by some users, for exampleto aid Emacs’ auto-fill mode.

Paragraphs

The paragraph is the most basic block in a reST document. Paragraphs are simplychunks of text separated by one or more blank lines. As in Python, indentationis significant in reST, so all lines of the same paragraph must be left-alignedto the same level of indentation.

Inline markup

The standard reST inline markup is quite simple: use

  • one asterisk:*text* for emphasis (italics),

  • two asterisks:**text** for strong emphasis (boldface), and

  • backquotes:``text`` for code samples, variables, and literals.

If asterisks or backquotes appear in running text and could be confused withinline markup delimiters, they have to be escaped with a backslash.

Be aware of some restrictions of this markup:

  • it may not be nested,

  • content may not start or end with whitespace:*text* is wrong,

  • it must be separated from surrounding text by non-word characters. Use abackslash escaped space to work around that:thisis\*one*\word.

These restrictions may be lifted in future versions of the docutils.

reST also allows for custom “interpreted text roles”, which signify that theenclosed text should be interpreted in a specific way. Sphinx uses this toprovide semantic markup and cross-referencing of identifiers, as described inthe appropriate section. The general syntax is:rolename:`content`.

Lists and quotes

List markup is natural: just place an asterisk at the start of a paragraph andindent properly. The same goes for numbered lists; they can also beautomatically numbered using a# sign:

* This is a bulleted list.* It has two items, the second  item uses two lines.1. This is a numbered list.2. It has two items too.#. This is a numbered list.#. It has two items too.

Nested lists are possible, but be aware that they must be separated from theparent list items by blank lines:

* this is* a list* with a nested list* and some subitems* and here the parent list continues

Definition lists are created as follows:

term (up to a line of text)   Definition of the term, which must be indented   and can even consist of multiple paragraphsnext term   Description.

Paragraphs are quoted by just indenting them more than the surroundingparagraphs.

Source code

Literal code blocks are introduced by ending a paragraph with the special marker::. The literal block must be indented:

This is a normal text paragraph. The next paragraph is a code sample::   It is not processed in any way, except   that the indentation is removed.   It can span multiple lines.This is a normal text paragraph again.

The handling of the:: marker is smart:

  • If it occurs as a paragraph of its own, that paragraph is completely leftout of the document.

  • If it is preceded by whitespace, the marker is removed.

  • If it is preceded by non-whitespace, the marker is replaced by a singlecolon.

That way, the second sentence in the above example’s first paragraph would berendered as “The next paragraph is a code sample:”.

Hyperlinks

External links

Use`Linktext<http://target>`_ for inline web links. If the link textshould be the web address, you don’t need special markup at all, the parserfinds links and mail addresses in ordinary text.

Internal links

Internal linking is done via a special reST role, see the section on specificmarkup,Cross-linking markup.

Sections

Section headers are created by underlining (and optionally overlining) thesection title with a punctuation character, at least as long as the text:

=================This is a heading=================

Normally, there are no heading levels assigned to certain characters as thestructure is determined from the succession of headings. However, for thePython documentation, here is a suggested convention:

  • # with overline, for parts

  • * with overline, for chapters

  • =, for sections

  • -, for subsections

  • ^, for subsubsections

  • ", for paragraphs

Explicit markup

“Explicit markup” is used in reST for most constructs that need specialhandling, such as footnotes, specially-highlighted paragraphs, comments, andgeneric directives.

An explicit markup block begins with a line starting with.. followed bywhitespace and is terminated by the next paragraph at the same level ofindentation. (There needs to be a blank line between explicit markup and normalparagraphs. This may all sound a bit complicated, but it is intuitive enoughwhen you write it.)

Directives

A directive is a generic block of explicit markup. Besides roles, it is one ofthe extension mechanisms of reST, and Sphinx makes heavy use of it.

Basically, a directive consists of a name, arguments, options and content. (Keepthis terminology in mind, it is used inthe next section describing customdirectives.) Looking at this example,

..function:: foo(x)              foo(y, z):bar: no   Return a line of text input from the user.

function is the directive name. It is given two arguments here, theremainder of the first line and the second line, as well as one optionbar(as you can see, options are given in the lines immediately following thearguments and indicated by the colons).

The directive content follows after a blank line and is indented relative to thedirective start.

Footnotes

For footnotes, use[#]_ to mark the footnote location, and add the footnotebody at the bottom of the document after a “Footnotes” rubric heading, like so:

Lorem ipsum[#]_ dolor sit amet ...[#]_..rubric:: Footnotes..[#] Text of the first footnote...[#] Text of the second footnote.

You can also explicitly number the footnotes for better context.

Comments

Every explicit markup block (starting with..) which isn’t avalid markup construct is regarded as a comment:

.. This is a comment

Source encoding

Since the easiest way to include special characters like em dashes or copyrightsigns in reST is to directly write them as Unicode characters, one has tospecify an encoding:

All Python documentation source files must be in UTF-8 encoding, and the HTMLdocuments written from them will be in that encoding as well.

Gotchas

There are some problems one commonly runs into while authoring reST documents:

  • Separation of inline markup: As said above, inline markup spans must beseparated from the surrounding text by non-word characters, you have to usean escaped space to get around that.

Typographic conventions

BigO notation

BigO notation is used to describe the performance of algorithms.

Use italics for the bigO and variables. For example:

reStructuredText

Rendered

*O*\(1)

O(1)

*O*\(log*n*)

O(logn)

*O*\(*n*)

O(n)

*O*\(*n*log*n*)

O(n logn)

*O*\(*n*\:sup:`2`)

O(n2)

Additional markup constructs

Sphinx adds a lot of new directives and interpreted text roles to standard reSTmarkup. This section contains the reference material for these facilities.Documentation for “standard” reST constructs is not included here, thoughthey are used in the Python documentation.

Note

This is just an overview of Sphinx’ extended markup capabilities; fullcoverage can be found inits own documentation.

Meta-information markup

sectionauthor

Identifies the author of the current section. The argument should includethe author’s name such that it can be used for presentation (though it isn’t)and email address. The domain name portion of the address should be lowercase. Example:

..sectionauthor:: Guido van Rossum <guido@python.org>

Currently, this markup isn’t reflected in the output in any way, but it helpskeep track of contributions.

Module-specific markup

The markup described in this section is used to provide information about amodule being documented. Each module should be documented in its own file.Normally this markup appears after the title heading of that file; a typicalfile might start like this:

:mod:`parrot` -- Dead parrot access===================================..module:: parrot:platform: Unix, Windows:synopsis: Analyze and reanimate dead parrots...moduleauthor:: Eric Cleese <eric@python.invalid>..moduleauthor:: John Idle <john@python.invalid>

As you can see, the module-specific markup consists of two directives, themodule directive and themoduleauthor directive.

module

This directive marks the beginning of the description of a module, package,or submodule. The name should be fully qualified (that is, including thepackage name for submodules).

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

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

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

moduleauthor

Themoduleauthor directive, which can appear multiple times, names theauthors of the module code, just likesectionauthor names the author(s)of a piece of documentation. It too does not result in any output currently.

Note

It is important to make the section title of a module-describing filemeaningful since that value will be inserted in the table-of-contents treesin overview files.

Information units

There are a number of directives used to describe specific features provided bymodules. Each directive requires one or more signatures to provide basicinformation about what is being described, and the content should be thedescription. The basic version makes entries in the general index; if no indexentry is desired, you can give the directive option flag:noindex:. Thefollowing example shows all of the features of this directive type:

..function:: spam(eggs)              ham(eggs):noindex:   Spam or ham the foo.

The signatures of object methods or data attributes should not include theclass name, but be nested in a class directive. The generated files willreflect this nesting, and the target identifiers (for HTML output) will useboth the class and method name, to enable consistent cross-references. If youdescribe methods belonging to an abstract protocol such as context managers,use a class directive with a (pseudo-)type name too to make theindex entries more informative.

The directives are:

c:function

Describes a C function. The signature should be given as in C, for example:

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

This is also used to describe function-like preprocessor macros. The namesof 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

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, howthe value should be interpreted, and whether the value can be changed.References to structure members in text should use themember role.

c:macro

Describes a “simple” C macro. Simple macros are macros which are usedfor code expansion, but which do not take arguments so cannot be described asfunctions. This is not to be used for simple constant definitions. Examplesof its use in the Python documentation includePyObject_HEAD andPy_BEGIN_ALLOW_THREADS.

c:type

Describes a C type. The signature should just be the type name.

c:var

Describes a global C variable. The signature should include the type, suchas:

..c:var:: PyObject* PyClass_Type
data

Describes global data in a module, including both variables and values usedas “defined constants.” Class and object attributes are not documentedusing this directive.

exception

Describes an exception class. The signature can, but need not includeparentheses with constructor arguments.

function

Describes a module-level function. The signature should include theparameters, enclosing optional parameters in brackets. Default values can begiven if it enhances clarity. For example:

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

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

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

coroutinefunction

Describes a module-level coroutine. The description should include similarinformation to that described forfunction.

decorator

Describes a decorator function. The signature shouldnot represent thesignature of the actual function, but the usage as a decorator. For example,given the functions

defremovename(func):func.__name__=''returnfuncdefsetnewname(name):defdecorator(func):func.__name__=namereturnfuncreturndecorator

the descriptions should look like this:

..decorator:: removename   Remove name of the decorated function...decorator:: setnewname(name)   Set name of the decorated function to*name*.

There is nodeco role to link to a decorator that is marked up withthis directive; rather, use the:func: role.

class

Describes a class. The signature can include parentheses with parameterswhich will be shown as the constructor arguments.

attribute

Describes an object data attribute. The description should includeinformation about the type of the data to be expected and whether it may bechanged directly. This directive should be nested in a class directive,like in this example:

..class:: Spam   Description of the class.   ..attribute:: ham      Description of the attribute.

Refer to an attribute using the:attr: role:

Use the:attr:`ham` attribute to spam the eggs.

If is also possible to document an attribute outside of a class directive,for example if the documentation for different attributes and methods issplit in multiple sections. The class name should then be includedexplicitly:

..attribute:: Spam.eggs
method

Describes an object method. The parameters should not include theselfparameter. The description should include similar information to thatdescribed forfunction. This directive should be nested in a classdirective, like in the example above.

coroutinemethod

Describes an object coroutine method. The parameters should not include theself parameter. The description should include similar information tothat described forfunction. This directive should be nested in aclass directive.

decoratormethod

Same asdecorator, but for decorators that are methods.

Refer to a decorator method using the:meth: role.

staticmethod

Describes an object static method. The description should include similarinformation to that described forfunction. This directive should benested in aclass directive.

classmethod

Describes an object class method. The parameters should not include thecls parameter. The description should include similar information tothat described forfunction. This directive should be nested in aclass directive.

abstractmethod

Describes an object abstract method. The description should include similarinformation to that described forfunction. This directive should benested in aclass directive.

opcode

Describes a Pythonbytecode instruction.

option

Describes a Python command line option or switch. Option argument namesshould be enclosed in angle brackets. Example:

..option:: -m <module>   Run a module as a script.
envvar

Describes an environment variable that Python uses or defines.

There is also a generic version of these directives:

describe

This directive produces the same formatting as the specific ones explainedabove but does not create index entries or cross-referencing targets. It isused, for example, to describe the directives in this document. Example:

..describe:: opcode   Describes a Python bytecode instruction.

Showing code examples

Examples of Python source code or interactive sessions are represented usingstandard reST literal blocks. They are started by a:: at the end of thepreceding paragraph and delimited by indentation.

Representing an interactive session requires including the prompts and outputalong with the Python code. No special markup is required for interactivesessions. After the last line of input or output is presented, there shouldbe no trailing prompt. An example of correct usage is:

>>>1+12

Syntax highlighting is handled in a smart way:

  • There is a “highlighting language” for each source file. By default,this is'python' as the majority of files will have to highlight Pythonsnippets.

  • Within Python highlighting mode, interactive sessions are recognizedautomatically and highlighted appropriately.

  • The highlighting language can be changed using thehighlightdirective, used as follows:

    ..highlight:: c

    This language is used until the nexthighlight directive isencountered.

  • Thecode-block directive can be used to specify the highlight languageof a single code block, for example:

    ..code-block::c#include<stdio.h>voidmain(){printf("Hello world!\n");}
  • The values normally used for the highlighting language are:

    • python (the default)

    • c

    • rest

    • none (no highlighting)

  • If highlighting with the current language fails, the block is not highlightedin any way.

Longer displays of verbatim text may be included by storing the example text inan external file containing only plain text. The file may be included using theliteralinclude directive. For example, to include the Python sourcefileexample.py, use:

..literalinclude:: example.py

The file name is relative to the current file’s path. Documentation-specificinclude files should be placed in theDoc/includes subdirectory.

Note

There is a standardinclude directive, but it raises errors if thefile is not found.literalinclude is preferred because it only emits awarning instead of raising an error.

Roles

Aspreviously mentioned, Sphinx usesinterpreted text roles of the form:rolename:`content`to insert semantic markup in documents.

In the CPython documentation, there are a couple common caseswhere simpler markup should be used:

  • *arg* (rendered asarg) for function and method arguments.

  • ``True``/``False``/``None`` forTrue/False/None.

In addition, the CPython documentation defines a few custom roles:

  • :cve:`YYYY-NNNNN`: link to a Common Vulnerabilities and Exposures entry.

  • :cwe:`NNN`: link to a Common Weakness Enumeration entry.

  • :gh:`ID`: link to a GitHub issue.

  • :issue:`ID`: link to a bugs.python.com issue.

  • :pypi:`NAME`: link to a project on PyPI.

  • :source:`PATH`: link to a source file on GitHub.

There are some additional facilities that make cross-referencing roles moreversatile:

  • You may supply an explicit title and reference target, like in reST directhyperlinks::role:`title<target>` will refer totarget, but the linktext will betitle.

  • If you prefix the content with!, no reference/hyperlink will be created.

  • For the Python object roles, if you prefix the content with~, the linktext will only be the last component of the target. For example,:meth:`~Queue.Queue.get` will refer toQueue.Queue.get but onlydisplayget as the link text.

    In HTML output, the link’stitle attribute (that might be shown as atool-tip on mouse-hover) will always be the full target name.

  • Combining~ and! (for example,:meth:`~!Queue.Queue.get`) is notsupported. You can obtain the same result by using! and the lastcomponent of the target (for example,:meth:`!get`).

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

mod

The name of a module; a dotted name may be used. This should also be usedfor package names.

func

The name of a Python function; dotted names may be used. The role textshould not include trailing parentheses to enhance readability. Theparentheses are stripped when searching for identifiers.

data

The name of a module-level variable or constant.

const

The name of a “defined” constant. This may be a C-language#defineor a Python variable that is not intended to be changed.

class

A class name; a dotted name may be used.

meth

The name of a method of an object. The role text should include the typename and the method name. A dotted name may be used.

attr

The name of a data attribute of an object.

exc

The name of an exception. A dotted name may be used.

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

Normally, names in these roles are searched first without any furtherqualification, then with the current module name prepended, then with thecurrent module and class name (if any) prepended. If you prefix the name with adot, this order is reversed. For example, in the documentation of thecodecs module,:func:`open` always refers to the built-in function,while:func:`.open` refers tocodecs.open().

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


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

c:data

The name of a C-language variable.

c:func

The name of a C-language function. Should include trailing parentheses.

c:macro

The name of a “simple” C macro, as defined above.

c:type

The name of a C-language type.

c:member

The name of a C type member, as defined above.


The following roles do not refer to objects, but can create cross-references orinternal links:

envvar

An environment variable. Index entries are generated.

keyword

The name of a Python keyword. Using this role will generate a link to thedocumentation of the keyword.True,False andNone do not usethis role, but simple code markup (``True``), given that they’refundamental to the language and should be known to any programmer.

option

A command-line option of Python. The leading hyphen(s) must be included.If a matchingcmdoption directive exists, it is linked to. For optionsof other programs or scripts, use simple``code`` markup.

token

The name of a grammar token (used in the reference manual to create linksbetween production displays).


The following role creates a cross-reference to the term in the glossary:

term

Reference to a term in the glossary. The glossary is created using theglossary directive containing a definition list with terms anddefinitions. It does not have to be in the same file as thetermmarkup, in fact, by default the Python docs have one global glossaryin theglossary.rst file.

If you use a term that’s not explained in a glossary, you’ll get a warningduring build.


The following roles don’t do anything special except formatting the textin a different style:

command

The name of an OS-level command, such asrm.

dfn

Mark the defining instance of a term in the text. (No index entries aregenerated.)

file

The name of a file or directory. Within the contents, you can use curlybraces to indicate a “variable” part, for example:

``spam`` is installed in:file:`/usr/lib/python2.{x}/site-packages` ...

In the built documentation, thex will be displayed differently toindicate that it is to be replaced by the Python minor version.

guilabel

Labels presented as part of an interactive user interface should be markedusingguilabel. This includes labels from text-based interfaces such asthose created usingcurses or other text-based libraries. Any labelused in the interface should be marked with this role, including buttonlabels, window titles, field names, menu and menu selection names, and evenvalues in selection lists.

kbd

Mark a sequence of keystrokes. What form the key sequence takes may dependon platform- or application-specific conventions. When there are no relevantconventions, the names of modifier keys should be spelled out, to improveaccessibility for new users and non-native speakers. For example, anxemacs key sequence may be marked like:kbd:`C-xC-f`, but withoutreference to a specific application or platform, the same sequence should bemarked as:kbd:`Control-xControl-f`.

mailheader

The name of an RFC 822-style mail header. This markup does not imply thatthe header is being used in an email message, but can be used to refer to anyheader of the same “style.” This is also used for headers defined by thevarious MIME specifications. The header name should be entered in the sameway it would normally be found in practice, with the camel-casing conventionsbeing preferred where there is more than one common usage. For example::mailheader:`Content-Type`.

makevar

The name of amake variable.

manpage

A reference to a Unix manual page including the section,for example,:manpage:`ls(1)`.

menuselection

Menu selections should be marked using themenuselection role. This isused to mark a complete sequence of menu selections, including selectingsubmenus and choosing a specific operation, or any subsequence of such asequence. The names of individual selections should be separated by-->.

For example, to mark the selection “Start > Programs”, use this markup:

:menuselection:`Start --> Programs`

When including a selection that includes some trailing indicator, such as theellipsis some operating systems use to indicate that the command opens adialog, the indicator should be omitted from the selection name.

mimetype

The name of a MIME type, or a component of a MIME type (the major or minorportion, taken alone).

newsgroup

The name of a Usenet newsgroup.

program

The name of an executable program. This may differ from the file name forthe executable for some platforms. In particular, the.exe (or other)extension should be omitted for Windows programs.

regexp

A regular expression. Quotes should not be included.

samp

A piece of literal text, such as code. Within the contents, you can usecurly braces to indicate a “variable” part, as in:file:.

If you don’t need the “variable part” indication, use the standard``code`` instead.

The following roles generate external links:

pep

A reference to a Python Enhancement Proposal. This generates appropriateindex entries. The text “PEPnumber“ is generated; in the HTML output,this text is a hyperlink to an online copy of the specified PEP. Suchhyperlinks should not be a substitute for properly documenting thelanguage in the manuals.

rfc

A reference to an Internet Request for Comments. This generates appropriateindex entries. The text “RFCnumber“ is generated; in the HTML output,this text is a hyperlink to an online copy of the specified RFC.

Note that there are no special roles for including hyperlinks as you can usethe standard reST markup for that purpose.

Cross-linking markup

To support cross-referencing to arbitrary sections in the documentation, thestandard reST labels are “abused” a bit: Every label must precede a sectiontitle; and every label name must be unique throughout the entire documentationsource.

You can then reference to these sections using the:ref:`label-name` role.

Example:

.._my-reference-label:Section to cross-reference--------------------------This is the text of the section.It refers to the section itself, see:ref:`my-reference-label`.

The:ref: invocation is replaced with the section title.

Alternatively, you can reference any label (not just section titles)if you provide the link text:ref:`linktext<reference-label>`.

Paragraph-level markup

These directives create short paragraphs and can be used inside informationunits as well as normal text:

note

An especially important bit of information about an API that a user should beaware of when using whatever bit of API the note pertains to. The content ofthe directive should be written in complete sentences and include allappropriate punctuation.

Example:

..note::   This function is not suitable for sending spam e-mails.
warning

An important bit of information about an API that a user should be aware ofwhen using whatever bit of API the warning pertains to. The content of thedirective should be written in complete sentences and include all appropriatepunctuation. In the interest of not scaring users away from pages filledwith warnings, this directive should only be chosen overnote forinformation regarding the possibility of crashes, data loss, or securityimplications.

versionadded

This directive documents the version of Python which added the describedfeature, or a part of it, to the library or C API. When this applies to anentire module, it should be placed at the top of the module section beforeany prose.When adding a new APIwith a directive(class,attribute,function,method,c:type, etc),aversionadded should be included at the end of its description block.

The first argument must be given and is the version in question.Instead of a specific version number, you can—and should—usethe wordnext, indicating that the API will first appear in theupcoming release.The second argument is optional and can be used to describe the details of the feature.

Example:

..function:: func()   Return foo and bar.   ..versionadded:: next

When a release is made, the release manager will change thenext tothe just-released version. For example, iffunc in the above example isreleased in 3.14, the snippet will be changed to:

..function:: func()   Return foo and bar.   ..versionadded:: 3.14

The tool to do this replacement isupdate_version_next.pyin the release-tools repository.

When adding documentation for a function that existed in a past version,but wasn’t documented yet, use the version number where the function wasadded instead ofnext.

versionchanged

Similar toversionadded, but describes when and what changed in the namedfeature in some way (new parameters, changed side effects, platform support,etc.). This onemust have the second argument (explanation of the change).

Example:

..function:: func(spam=False)   Return foo and bar, optionally with*spam* applied.   ..versionchanged:: next      Added the*spam* parameter.

Note that there should be no blank line between the directive head and theexplanation; this is to make these blocks visually continuous in the markup.

deprecated

Indicates the version from which the described feature is deprecated.

There is one required argument: the version from which the feature isdeprecated.Similarly toversionadded, you should use the wordnext to indicatethe API will be first deprecated in the upcoming release.

Example:

..deprecated:: next
deprecated-removed

Likedeprecated, but it also indicates in which version the feature isremoved.

There are two required arguments: the version from which the feature isdeprecated (usuallynext), and the version in which the featureis removed, which must be a specific version number (notnext).

Example:

..deprecated-removed:: next 4.0
impl-detail

This directive is used to mark CPython-specific information. Use either witha block content or a single sentence as an argument, that is, either

..impl-detail::   This describes some implementation detail.   More explanation.

or

..impl-detail:: This shortly mentions an implementation detail.

CPython implementation detail:“ is automatically prepended to thecontent.

seealso

Many sections include a list of references to module documentation orexternal documents. These lists are created using theseealso directive.

Theseealso directive is typically placed in a section just before anysub-sections. For the HTML output, it is shown boxed off from the main flowof the text.

The content of theseealso directive should be a reST definition list.Example:

..seealso::   Module:mod:`zipfile`      Documentation of the:mod:`zipfile` standard module.`GNU tar manual, Basic Tar Format<http://link>`_      Documentation for tar archive files, including GNU tar extensions.
rubric

This directive creates a paragraph heading that is not used to create atable of contents node. It is currently used for the “Footnotes” caption.

centered

This directive creates a centered boldfaced paragraph. Use it as follows:

..centered::   Paragraph contents.

Table-of-contents markup

Since reST does not have facilities to interconnect several documents, or splitdocuments into multiple output files, Sphinx uses a custom directive to addrelations between the single files the documentation is made of, as well astables of contents. Thetoctree directive is the central element.

toctree

This directive inserts a “TOC tree” at the current location, using theindividual TOCs (including “sub-TOC trees”) of the files given in thedirective body. A numericmaxdepth option may be given to indicate thedepth of the tree; by default, all levels are included.

Consider this example (taken from the library reference index):

..toctree:::maxdepth: 2   intro   strings   datatypes   numeric   (many more files listed here)

This accomplishes two things:

  • Tables of contents from all those files are inserted, with a maximum depthof two, that means one nested heading.toctree directives in thosefiles are also taken into account.

  • Sphinx knows that the relative order of the filesintro,strings and so forth, and it knows that they are children of theshown file, the library index. From this information it generates “nextchapter”, “previous chapter” and “parent chapter” links.

In the end, all files included in the build process must occur in onetoctree directive; Sphinx will emit a warning if it finds a file that isnot included, because that means that this file will not be reachable throughstandard navigation.

The special filecontents.rst at the root of the source directory is the“root” of the TOC tree hierarchy; from it the “Contents” page is generated.

Index-generating markup

Sphinx automatically creates index entries from all information units (likefunctions, classes or attributes) like discussed before.

However, there is also an explicit directive available, to make the index morecomprehensive and enable index entries in documents where information is notmainly contained in information units, such as the language reference.

The directive isindex and contains one or more index entries. Each entryconsists of a type and a value, separated by a colon.

For example:

..index::   single: execution; context   module: __main__   module: sys   triple: module; search; path

This directive contains five entries, which will be converted to entries in thegenerated index which link to the exact location of the index statement (or, incase of offline media, the corresponding page number).

The possible entry types are:

single

Creates a single index entry. Can be made a subentry by separating thesubentry text with a semicolon (this notation is also used below to describewhat entries are created).

pair

pair:loop;statement is a shortcut that creates two index entries,namelyloop;statement andstatement;loop.

triple

Likewise,triple:module;search;path is a shortcut that creates threeindex entries, which aremodule;searchpath,search;path,moduleandpath;modulesearch.

module, keyword, operator, object, exception, statement, builtin

These all create two index entries. For example,module:hashlibcreates the entriesmodule;hashlib andhashlib;module. Thebuiltin entry type is slightly different in that “built-in function” is usedin place of “builtin” when creating the two entries.

For index directives containing only “single” entries, there is a shorthandnotation:

..index:: BNF, grammar, syntax, notation

This creates four index entries.

Grammar production displays

Special markup is available for displaying the productions of a formal grammar.The markup is simple and does not attempt to model all aspects of BNF (or anyderived forms), but provides enough to allow context-free grammars to bedisplayed in a way that causes uses of a symbol to be rendered as hyperlinks tothe definition of the symbol. There is this directive:

productionlist

This directive is used to enclose a group of productions. Each production isgiven on a single line and consists of a name, separated by a colon from thefollowing definition. If the definition spans multiple lines, eachcontinuation line must begin with a colon placed at the same column as in thefirst line.

Blank lines are not allowed withinproductionlist directive arguments.

The definition can contain token names which are marked as interpreted text(for example,unaryneg::="-"`integer`) – this generates cross-referencesto the productions of these tokens.

Note that no further reST parsing is done in the production, so that youdon’t have to escape* or| characters.

The following is an example taken from the Python Reference Manual:

..productionlist::   try_stmt: try1_stmt | try2_stmt   try1_stmt: "try" ":"`suite`            : ("except" [`expression` [","`target`]] ":"`suite`)+            : ["else" ":"`suite`]            : ["finally" ":"`suite`]   try2_stmt: "try" ":"`suite`            : "finally" ":"`suite`

Substitutions

The documentation system provides three substitutions that are defined bydefault. They are set in the build configuration fileconf.py.

|release|

Replaced by the Python release the documentation refers to. This is the fullversion string including alpha/beta/release candidate tags, for example,2.5.2b3.

|version|

Replaced by the Python version the documentation refers to. This consistsonly of the major and minor version parts, for example,2.5, even for version2.5.1.

|today|

Replaced by either today’s date, or the date set in the build configurationfile. Normally has the formatApril14,2007.

On this page

[8]ページ先頭

©2009-2025 Movatter.jp