From c4daa95c09acd8041d274d24f1c31c31d2adb0cf Mon Sep 17 00:00:00 2001 From: Adam Turner <9087854+aa-turner@users.noreply.github.com> Date: Tue, 14 Jan 2025 15:55:02 +0000 Subject: [PATCH] Enable the entire D category in Ruff --- .ruff.toml | 66 ++++++---------- sphinx/application.py | 3 +- sphinx/builders/__init__.py | 7 +- sphinx/builders/_epub_base.py | 3 +- sphinx/builders/changes.py | 4 +- sphinx/builders/dirhtml.py | 3 +- sphinx/builders/epub3.py | 3 +- sphinx/builders/gettext.py | 12 +-- sphinx/builders/html/__init__.py | 4 +- sphinx/builders/latex/__init__.py | 4 +- sphinx/builders/linkcheck.py | 4 +- sphinx/builders/manpage.py | 4 +- sphinx/builders/singlehtml.py | 5 +- sphinx/builders/texinfo.py | 4 +- sphinx/builders/xml.py | 8 +- sphinx/cmd/build.py | 8 +- sphinx/directives/__init__.py | 63 +++++++-------- sphinx/directives/code.py | 9 +-- sphinx/directives/other.py | 37 +++------ sphinx/domains/__init__.py | 6 +- sphinx/domains/_index.py | 6 +- sphinx/domains/c/__init__.py | 10 +-- sphinx/domains/c/_parser.py | 3 +- sphinx/domains/changeset.py | 4 +- sphinx/domains/citation.py | 3 +- sphinx/domains/cpp/__init__.py | 6 +- sphinx/domains/cpp/_ids.py | 3 +- sphinx/domains/cpp/_parser.py | 3 +- sphinx/domains/index.py | 4 +- sphinx/domains/javascript.py | 7 +- sphinx/domains/python/__init__.py | 15 +--- sphinx/domains/python/_object.py | 3 +- sphinx/domains/rst.py | 16 +--- sphinx/domains/std/__init__.py | 30 ++----- sphinx/environment/__init__.py | 3 +- sphinx/ext/apidoc/_generate.py | 3 +- sphinx/ext/autodoc/__init__.py | 74 ++++++----------- sphinx/ext/autodoc/importer.py | 4 +- sphinx/ext/autosummary/__init__.py | 6 +- sphinx/ext/coverage.py | 4 +- sphinx/ext/doctest.py | 8 +- sphinx/ext/extlinks.py | 6 +- sphinx/ext/graphviz.py | 8 +- sphinx/ext/inheritance_diagram.py | 22 ++---- sphinx/ext/napoleon/docstring.py | 9 +-- sphinx/ext/todo.py | 8 +- sphinx/io.py | 13 +-- sphinx/jinja2glue.py | 10 +-- sphinx/locale/__init__.py | 3 +- sphinx/parsers.py | 13 +-- sphinx/pygments_styles.py | 7 +- sphinx/roles.py | 6 +- sphinx/search/__init__.py | 29 +++---- sphinx/search/ja.py | 6 +- sphinx/search/zh.py | 4 +- sphinx/testing/fixtures.py | 27 ++----- sphinx/testing/path.py | 79 +++++-------------- sphinx/transforms/__init__.py | 45 +++-------- sphinx/transforms/i18n.py | 20 ++--- sphinx/transforms/post_transforms/__init__.py | 4 +- sphinx/transforms/post_transforms/code.py | 6 +- sphinx/util/_files.py | 3 +- sphinx/util/docfields.py | 9 +-- sphinx/util/docutils.py | 6 +- sphinx/util/nodes.py | 6 +- sphinx/writers/html5.py | 4 +- sphinx/writers/manpage.py | 7 +- .../roots/test-ext-autodoc/target/__init__.py | 8 +- .../test-ext-autodoc/target/empty_all.py | 4 +- .../target/inherited_annotations.py | 3 +- .../target/process_docstring.py | 3 +- .../test-ext-autosummary-ext/dummy_module.py | 12 +-- .../underscore_module_.py | 4 +- .../test-ext-doctest-with-autodoc/dir/bar.py | 5 +- .../test-ext-doctest-with-autodoc/foo.py | 6 +- .../test-ext-napoleon/mypackage/typehints.py | 3 +- .../subpackage/_subpackage2/submodule.py | 16 +--- .../not_a_package/submodule.py | 12 +-- tests/roots/test-ext-viewcode/spam/mod1.py | 16 +--- tests/roots/test-ext-viewcode/spam/mod2.py | 12 +-- tests/roots/test-inheritance/dummy/test.py | 4 +- tests/roots/test-root/autodoc_target.py | 12 +-- tests/roots/test-warnings/autodoc_fodder.py | 3 +- .../test_build_html_copyright.py | 3 +- tests/test_builders/test_build_linkcheck.py | 3 +- .../ext_napoleon_pep526_data_numpy.py | 3 +- tests/test_extensions/test_ext_autodoc.py | 7 +- tests/test_extensions/test_ext_napoleon.py | 4 +- tests/test_extensions/test_ext_todo.py | 3 +- tests/test_extensions/test_ext_viewcode.py | 7 +- tests/test_markup/test_metadata.py | 3 +- tests/test_search.py | 3 +- tests/test_util/test_util_inspect.py | 10 +-- tests/test_util/test_util_nodes.py | 3 +- tests/utils.py | 9 +-- utils/babel_runner.py | 3 +- 96 files changed, 310 insertions(+), 706 deletions(-) diff --git a/.ruff.toml b/.ruff.toml index 069c12af6..15db85945 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -33,6 +33,18 @@ ignore = [ "COM812", # Trailing comma missing # flake8-copyright "CPY001", # Missing copyright notice at top of file + # pydocstyle ('D') + "D100", # Missing docstring in public module + "D101", # Missing docstring in public class + "D102", # Missing docstring in public method + "D103", # Missing docstring in public function + "D104", # Missing docstring in public package + "D105", # Missing docstring in magic method + "D107", # Missing docstring in `__init__` + "D200", # One-line docstring should fit on one line + "D205", # 1 blank line required between summary line and description + "D400", # First line should end with a period + "D401", # First line of docstring should be in imperative mood: "{first_line}" # pycodestyle "E741", # Ambiguous variable name: `{name}` # eradicate @@ -152,51 +164,11 @@ select = [ # flake8-copyright ('CPY') "CPY", # pydocstyle ('D') -# "D100", # Missing docstring in public module -# "D101", # Missing docstring in public class -# "D102", # Missing docstring in public method -# "D103", # Missing docstring in public function -# "D104", # Missing docstring in public package -# "D105", # Missing docstring in magic method - "D106", # Missing docstring in public nested class -# "D107", # Missing docstring in `__init__` -# "D200", # One-line docstring should fit on one line - "D201", # No blank lines allowed before function docstring (found {num_lines}) - "D202", # No blank lines allowed after function docstring (found {num_lines}) - "D204", # 1 blank line required after class docstring -# "D205", # 1 blank line required between summary line and description - "D206", # Docstring should be indented with spaces, not tabs - "D207", # Docstring is under-indented - "D208", # Docstring is over-indented - "D209", # Multi-line docstring closing quotes should be on a separate line - "D210", # No whitespaces allowed surrounding docstring text - "D211", # No blank lines allowed before class docstring -# "D212", # Multi-line docstring summary should start at the first line -# "D213", # Multi-line docstring summary should start at the second line -# "D214", # Section is over-indented ("{name}") -# "D215", # Section underline is over-indented ("{name}") - "D300", # Use triple double quotes `"""` - "D301", # Use `r"""` if any backslashes in a docstring -# "D400", # First line should end with a period -# "D401", # First line of docstring should be in imperative mood: "{first_line}" - "D402", # First line should not be the function's signature - "D403", # First word of the first line should be capitalized: `{}` -> `{}` -# "D404", # First word of the docstring should not be "This" - "D405", # Section name should be properly capitalized ("{name}") -# "D406", # Section name should end with a newline ("{name}") -# "D407", # Missing dashed underline after section ("{name}") - "D408", # Section underline should be in the line following the section's name ("{name}") - "D409", # Section underline should match the length of its name ("{name}") - "D410", # Missing blank line after section ("{name}") - "D411", # Missing blank line before section ("{name}") -# "D412", # No blank lines allowed between a section header and its content ("{name}") -# "D413", # Missing blank line after last section ("{name}") - "D414", # Section has no content ("{name}") -# "D415", # First line should end with a period, question mark, or exclamation point - "D416", # Section name should end with a colon ("{name}") + "D", + "D212", # Multi-line docstring summary should start at the first line + # "D404", # First word of the docstring should not be "This" + # "D415", # First line should end with a period, question mark, or exclamation point "D417", # Missing argument description in the docstring for `{definition}`: `{name}` - "D418", # Function decorated with `@overload` shouldn't contain a docstring - "D419", # Docstring is empty # flake8-django ('DJ') # Django is not used in Sphinx # flake8-datetimez ('DTZ') @@ -294,6 +266,7 @@ select = [ # flake8-2020 ('YTT') "YTT", ] + logger-objects = [ "sphinx.ext.apidoc._shared.LOGGER", "sphinx.ext.intersphinx._shared.LOGGER", @@ -412,3 +385,8 @@ forced-separate = [ required-imports = [ "from __future__ import annotations", ] + +[lint.pydocstyle] +convention = "pep257" +ignore-decorators = ["typing.overload"] +ignore-var-parameters = true diff --git a/sphinx/application.py b/sphinx/application.py index 2531c336f..8cf47393c 100644 --- a/sphinx/application.py +++ b/sphinx/application.py @@ -1803,8 +1803,7 @@ class Sphinx: class TemplateBridge: - """ - This class defines the interface for a "template bridge", that is, a class + """This class defines the interface for a "template bridge", that is, a class that renders templates given a template name and a context. """ diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py index 66beb3f98..b8ad8b138 100644 --- a/sphinx/builders/__init__.py +++ b/sphinx/builders/__init__.py @@ -66,9 +66,7 @@ logger = logging.getLogger(__name__) class Builder: - """ - Builds target formats from the reST sources. - """ + """Builds target formats from the reST sources.""" #: The builder's name. #: This is the value used to select builders on the command line. @@ -812,8 +810,7 @@ class Builder: pass def write_doc(self, docname: str, doctree: nodes.document) -> None: - """ - Write the output file for the document + """Write the output file for the document :param docname: the :term:`docname `. :param doctree: defines the content to be written. diff --git a/sphinx/builders/_epub_base.py b/sphinx/builders/_epub_base.py index 0e4456f81..441bb7148 100644 --- a/sphinx/builders/_epub_base.py +++ b/sphinx/builders/_epub_base.py @@ -126,8 +126,7 @@ ssp = sphinx_smarty_pants class EpubBuilder(StandaloneHTMLBuilder): - """ - Builder that outputs epub files. + """Builder that outputs epub files. It creates the metainfo files container.opf, toc.ncx, mimetype, and META-INF/container.xml. Afterwards, all necessary files are zipped to an diff --git a/sphinx/builders/changes.py b/sphinx/builders/changes.py index 3ce79947c..b9341df90 100644 --- a/sphinx/builders/changes.py +++ b/sphinx/builders/changes.py @@ -25,9 +25,7 @@ logger = logging.getLogger(__name__) class ChangesBuilder(Builder): - """ - Write a summary with all versionadded/changed/deprecated/removed directives. - """ + """Write a summary with all versionadded/changed/deprecated/removed directives.""" name = 'changes' epilog = __('The overview file is in %(outdir)s.') diff --git a/sphinx/builders/dirhtml.py b/sphinx/builders/dirhtml.py index 2ae1e35a7..5a2819bf7 100644 --- a/sphinx/builders/dirhtml.py +++ b/sphinx/builders/dirhtml.py @@ -17,8 +17,7 @@ logger = logging.getLogger(__name__) class DirectoryHTMLBuilder(StandaloneHTMLBuilder): - """ - A StandaloneHTMLBuilder that creates all HTML pages as "index.html" in + """A StandaloneHTMLBuilder that creates all HTML pages as "index.html" in a directory given by their pagename, so that generated URLs don't have ``.html`` in them. """ diff --git a/sphinx/builders/epub3.py b/sphinx/builders/epub3.py index 6c3a89afe..23528adcf 100644 --- a/sphinx/builders/epub3.py +++ b/sphinx/builders/epub3.py @@ -73,8 +73,7 @@ _XML_NAME_PATTERN = re.compile(f'({_xml_name_start_char})({_xml_name_char})*') class Epub3Builder(_epub_base.EpubBuilder): - """ - Builder that outputs epub3 files. + """Builder that outputs epub3 files. It creates the metainfo files content.opf, nav.xhtml, toc.ncx, mimetype, and META-INF/container.xml. Afterwards, all necessary files are zipped to diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py index 844f1ff3c..9b6145fbe 100644 --- a/sphinx/builders/gettext.py +++ b/sphinx/builders/gettext.py @@ -98,9 +98,7 @@ class Catalog: class MsgOrigin: - """ - Origin holder for Catalog message origin. - """ + """Origin holder for Catalog message origin.""" __slots__ = 'source', 'line', 'uid' @@ -158,9 +156,7 @@ class I18nTags(Tags): class I18nBuilder(Builder): - """ - General i18n builder. - """ + """General i18n builder.""" name = 'i18n' versioning_method = 'text' @@ -242,9 +238,7 @@ def _is_node_in_substitution_definition(node: nodes.Node) -> bool: class MessageCatalogBuilder(I18nBuilder): - """ - Builds gettext-style message catalogs (.pot files). - """ + """Builds gettext-style message catalogs (.pot files).""" name = 'gettext' epilog = __('The message catalogs are in %(outdir)s.') diff --git a/sphinx/builders/html/__init__.py b/sphinx/builders/html/__init__.py index 7d4271315..886840c37 100644 --- a/sphinx/builders/html/__init__.py +++ b/sphinx/builders/html/__init__.py @@ -105,9 +105,7 @@ def convert_locale_to_language_tag(locale: str | None) -> str | None: class StandaloneHTMLBuilder(Builder): - """ - Builds standalone HTML docs. - """ + """Builds standalone HTML docs.""" name = 'html' format = 'html' diff --git a/sphinx/builders/latex/__init__.py b/sphinx/builders/latex/__init__.py index b5024f7fb..268add92f 100644 --- a/sphinx/builders/latex/__init__.py +++ b/sphinx/builders/latex/__init__.py @@ -111,9 +111,7 @@ logger = logging.getLogger(__name__) class LaTeXBuilder(Builder): - """ - Builds LaTeX output to create PDF. - """ + """Builds LaTeX output to create PDF.""" name = 'latex' format = 'latex' diff --git a/sphinx/builders/linkcheck.py b/sphinx/builders/linkcheck.py index 0a2e2b252..4b8dd2b0e 100644 --- a/sphinx/builders/linkcheck.py +++ b/sphinx/builders/linkcheck.py @@ -72,9 +72,7 @@ DEFAULT_DELAY = 60.0 class CheckExternalLinksBuilder(DummyBuilder): - """ - Checks for broken external links. - """ + """Checks for broken external links.""" name = 'linkcheck' epilog = __('Look for any errors in the above output or in %(outdir)s/output.txt') diff --git a/sphinx/builders/manpage.py b/sphinx/builders/manpage.py index 0ee1a678c..d0c144187 100644 --- a/sphinx/builders/manpage.py +++ b/sphinx/builders/manpage.py @@ -31,9 +31,7 @@ logger = logging.getLogger(__name__) class ManualPageBuilder(Builder): - """ - Builds groff output in manual page format. - """ + """Builds groff output in manual page format.""" name = 'man' format = 'man' diff --git a/sphinx/builders/singlehtml.py b/sphinx/builders/singlehtml.py index efa410f41..d3b8ed77b 100644 --- a/sphinx/builders/singlehtml.py +++ b/sphinx/builders/singlehtml.py @@ -29,10 +29,7 @@ logger = logging.getLogger(__name__) class SingleFileHTMLBuilder(StandaloneHTMLBuilder): - """ - A StandaloneHTMLBuilder subclass that puts the whole document tree on one - HTML page. - """ + """Builds the whole document tree as a single HTML page.""" name = 'singlehtml' epilog = __('The HTML page is in %(outdir)s.') diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py index 1f19f0cc3..5465e2588 100644 --- a/sphinx/builders/texinfo.py +++ b/sphinx/builders/texinfo.py @@ -39,9 +39,7 @@ template_dir = os.path.join(package_dir, 'templates', 'texinfo') class TexinfoBuilder(Builder): - """ - Builds Texinfo output to create Info documentation. - """ + """Builds Texinfo output to create Info documentation.""" name = 'texinfo' format = 'texinfo' diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py index 0cb2dfae7..e50d6f2b0 100644 --- a/sphinx/builders/xml.py +++ b/sphinx/builders/xml.py @@ -29,9 +29,7 @@ logger = logging.getLogger(__name__) class XMLBuilder(Builder): - """ - Builds Docutils-native XML. - """ + """Builds Docutils-native XML.""" name = 'xml' format = 'xml' @@ -101,9 +99,7 @@ class XMLBuilder(Builder): class PseudoXMLBuilder(XMLBuilder): - """ - Builds pseudo-XML for display purposes. - """ + """Builds pseudo-XML for display purposes.""" name = 'pseudoxml' format = 'pseudoxml' diff --git a/sphinx/cmd/build.py b/sphinx/cmd/build.py index 2af76bc4b..c1441b68f 100644 --- a/sphinx/cmd/build.py +++ b/sphinx/cmd/build.py @@ -50,10 +50,10 @@ def handle_exception( def jobs_argument(value: str) -> int: - """ - Special type to handle 'auto' flags passed to 'sphinx-build' via -j flag. Can - be expanded to handle other special scaling requests, such as setting job count - to cpu_count. + """Parse the ``--jobs`` flag. + + Return the number of CPUs if 'auto' is used, + otherwise ensure *value* is a positive integer. """ if value == 'auto': return multiprocessing.cpu_count() diff --git a/sphinx/directives/__init__.py b/sphinx/directives/__init__.py index e31347105..d74a9bac4 100644 --- a/sphinx/directives/__init__.py +++ b/sphinx/directives/__init__.py @@ -30,9 +30,7 @@ strip_backslash_re = re.compile(r'\\(.)') def optional_int(argument: str) -> int | None: - """ - Check for an integer argument or None value; raise ``ValueError`` if not. - """ + """Check for an integer argument or None value; raise ``ValueError`` if not.""" if argument is None: return None else: @@ -47,10 +45,10 @@ ObjDescT = TypeVar('ObjDescT') class ObjectDescription(SphinxDirective, Generic[ObjDescT]): - """ - Directive to describe a class, function or similar object. Not used - directly, but subclassed (in domain-specific directives) to add custom - behavior. + """Directive to describe a class, function or similar object. + + Not used directly, but subclassed (in domain-specific directives) + to add custom behaviour. """ has_content = True @@ -91,9 +89,9 @@ class ObjectDescription(SphinxDirective, Generic[ObjDescT]): return self._doc_field_type_map def get_signatures(self) -> list[str]: - """ - Retrieve the signatures to document from the directive arguments. By - default, signatures are given as arguments, one per line. + """Retrieve the signatures to document from the directive arguments. + + By default, signatures are given as arguments, one per line. """ lines = nl_escape_re.sub('', self.arguments[0]).split('\n') if self.config.strip_signature_backslash: @@ -103,9 +101,10 @@ class ObjectDescription(SphinxDirective, Generic[ObjDescT]): return [line.strip() for line in lines] def handle_signature(self, sig: str, signode: desc_signature) -> ObjDescT: - """ - Parse the signature *sig* into individual nodes and append them to - *signode*. If ValueError is raised, parsing is aborted and the whole + """Parse the signature *sig*. + + The individual nodes are then appended to *signode*. + If ValueError is raised, parsing is aborted and the whole *sig* is put into a single desc_name node. The return value should be a value that identifies the object. It is @@ -117,39 +116,39 @@ class ObjectDescription(SphinxDirective, Generic[ObjDescT]): def add_target_and_index( self, name: ObjDescT, sig: str, signode: desc_signature ) -> None: - """ - Add cross-reference IDs and entries to self.indexnode, if applicable. + """Add cross-reference IDs and entries to self.indexnode, if applicable. *name* is whatever :meth:`handle_signature()` returned. """ pass # do nothing by default def before_content(self) -> None: - """ - Called before parsing content. Used to set information about the current - directive context on the build environment. + """Called before parsing content. + + Used to set information about the current directive context + on the build environment. """ pass def transform_content(self, content_node: addnodes.desc_content) -> None: - """ + """Can be used to manipulate the content. + Called after creating the content through nested parsing, but before the ``object-description-transform`` event is emitted, and before the info-fields are transformed. - Can be used to manipulate the content. """ pass def after_content(self) -> None: - """ - Called after parsing content. Used to reset information about the - current directive context on the build environment. + """Called after parsing content. + + Used to reset information about the current directive context + on the build environment. """ pass def _object_hierarchy_parts(self, sig_node: desc_signature) -> tuple[str, ...]: - """ - Returns a tuple of strings, one entry for each part of the object's + """Returns a tuple of strings, one entry for each part of the object's hierarchy (e.g. ``('module', 'submodule', 'Class', 'method')``). The returned tuple is used to properly nest children within parents in the table of contents, and can also be used within the @@ -160,8 +159,7 @@ class ObjectDescription(SphinxDirective, Generic[ObjDescT]): return () def _toc_entry_name(self, sig_node: desc_signature) -> str: - """ - Returns the text of the table of contents entry for the object. + """Returns the text of the table of contents entry for the object. This function is called once, in :py:meth:`run`, to set the name for the table of contents entry (a special attribute ``_toc_name`` is set on the @@ -186,8 +184,7 @@ class ObjectDescription(SphinxDirective, Generic[ObjDescT]): return '' def run(self) -> list[Node]: - """ - Main directive entry function, called by docutils upon encountering the + """Main directive entry function, called by docutils upon encountering the directive. This directive is meant to be quite easily subclassable, so it delegates @@ -321,9 +318,7 @@ class ObjectDescription(SphinxDirective, Generic[ObjDescT]): class DefaultRole(SphinxDirective): - """ - Set the default interpreted text role. Overridden from docutils. - """ + """Set the default interpreted text role. Overridden from docutils.""" optional_arguments = 1 final_argument_whitespace = False @@ -353,9 +348,7 @@ class DefaultRole(SphinxDirective): class DefaultDomain(SphinxDirective): - """ - Directive to (re-)set the default domain for this source file. - """ + """Directive to (re-)set the default domain for this source file.""" has_content = False required_arguments = 1 diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py index 00567bdfe..e94b18a18 100644 --- a/sphinx/directives/code.py +++ b/sphinx/directives/code.py @@ -30,8 +30,7 @@ logger = logging.getLogger(__name__) class Highlight(SphinxDirective): - """ - Directive to set the highlighting language for code blocks, as well + """Directive to set the highlighting language for code blocks, as well as the threshold for line numbers. """ @@ -98,8 +97,7 @@ def container_wrapper( class CodeBlock(SphinxDirective): - """ - Directive for a code block with special highlighting or line numbering + """Directive for a code block with special highlighting or line numbering settings. """ @@ -411,8 +409,7 @@ class LiteralIncludeReader: class LiteralInclude(SphinxDirective): - """ - Like ``.. include:: :literal:``, but only warns if the include file is + """Like ``.. include:: :literal:``, but only warns if the include file is not found, and does not raise errors. Also has several options for selecting what to include. """ diff --git a/sphinx/directives/other.py b/sphinx/directives/other.py index 4f5a502d5..4ab17cc70 100644 --- a/sphinx/directives/other.py +++ b/sphinx/directives/other.py @@ -41,8 +41,7 @@ def int_or_nothing(argument: str) -> int: class TocTree(SphinxDirective): - """ - Directive to notify Sphinx about the hierarchical structure of the docs, + """Directive to notify Sphinx about the hierarchical structure of the docs, and to include a table-of-contents like tree in the current document. """ @@ -89,9 +88,7 @@ class TocTree(SphinxDirective): return [wrappernode] def parse_content(self, toctree: addnodes.toctree) -> None: - """ - Populate ``toctree['entries']`` and ``toctree['includefiles']`` from content. - """ + """Populate ``toctree['entries']`` and ``toctree['includefiles']`` from content.""" generated_docnames = frozenset(StandardDomain._virtual_doc_names) suffixes = self.config.source_suffix current_docname = self.env.docname @@ -184,8 +181,7 @@ class TocTree(SphinxDirective): class Author(SphinxDirective): - """ - Directive to give the name of the author of the current document + """Directive to give the name of the author of the current document or section. Shown in the output only if the show_authors option is on. """ @@ -219,17 +215,13 @@ class Author(SphinxDirective): class SeeAlso(BaseAdmonition): - """ - An admonition mentioning things to look at as reference. - """ + """An admonition mentioning things to look at as reference.""" node_class = addnodes.seealso class TabularColumns(SphinxDirective): - """ - Directive to give an explicit tabulary column definition to LaTeX. - """ + """Directive to give an explicit tabulary column definition to LaTeX.""" has_content = False required_arguments = 1 @@ -245,9 +237,7 @@ class TabularColumns(SphinxDirective): class Centered(SphinxDirective): - """ - Directive to create a centered line of bold text. - """ + """Directive to create a centered line of bold text.""" has_content = False required_arguments = 1 @@ -268,9 +258,7 @@ class Centered(SphinxDirective): class Acks(SphinxDirective): - """ - Directive for a list of names. - """ + """Directive for a list of names.""" has_content = True required_arguments = 0 @@ -290,9 +278,7 @@ class Acks(SphinxDirective): class HList(SphinxDirective): - """ - Directive for a list that gets compacted horizontally. - """ + """Directive for a list that gets compacted horizontally.""" has_content = True required_arguments = 0 @@ -327,9 +313,7 @@ class HList(SphinxDirective): class Only(SphinxDirective): - """ - Directive to only include text if the given tag(s) are enabled. - """ + """Directive to only include text if the given tag(s) are enabled.""" has_content = True required_arguments = 1 @@ -389,8 +373,7 @@ class Only(SphinxDirective): class Include(BaseInclude, SphinxDirective): - """ - Like the standard "Include" directive, but interprets absolute paths + """Like the standard "Include" directive, but interprets absolute paths "correctly", i.e. relative to source directory. """ diff --git a/sphinx/domains/__init__.py b/sphinx/domains/__init__.py index 53ff96f8d..c7318ae50 100644 --- a/sphinx/domains/__init__.py +++ b/sphinx/domains/__init__.py @@ -36,8 +36,7 @@ __all__ = ( class ObjType: - """ - An ObjType is the description for a type of object that a domain can + """An ObjType is the description for a type of object that a domain can document. In the object_types attribute of Domain subclasses, object type names are mapped to instances of this class. @@ -61,8 +60,7 @@ class ObjType: class Domain: - """ - A Domain is meant to be a group of "object" description directives for + """A Domain is meant to be a group of "object" description directives for objects of a similar nature, and corresponding roles to create references to them. Examples would be Python modules, classes, functions etc., elements of a templating language, Sphinx roles and directives, etc. diff --git a/sphinx/domains/_index.py b/sphinx/domains/_index.py index 3c263bff7..afb5be400 100644 --- a/sphinx/domains/_index.py +++ b/sphinx/domains/_index.py @@ -14,8 +14,7 @@ if TYPE_CHECKING: class IndexEntry(NamedTuple): - """ - An index entry. + """An index entry. .. note:: @@ -53,8 +52,7 @@ class IndexEntry(NamedTuple): class Index(ABC): - """ - An Index is the description for a domain-specific index. To add an index to + """An Index is the description for a domain-specific index. To add an index to a domain, subclass Index, overriding the three name attributes: * `name` is an identifier used for generating file names. diff --git a/sphinx/domains/c/__init__.py b/sphinx/domains/c/__init__.py index 4b1dce00a..d884e8d17 100644 --- a/sphinx/domains/c/__init__.py +++ b/sphinx/domains/c/__init__.py @@ -106,9 +106,7 @@ def _make_phony_error_name() -> ASTNestedName: class CObject(ObjectDescription[ASTDeclaration]): - """ - Description of a C language object. - """ + """Description of a C language object.""" option_spec: ClassVar[OptionSpec] = { 'no-index-entry': directives.flag, @@ -383,8 +381,7 @@ class CTypeObject(CObject): class CNamespaceObject(SphinxDirective): - """ - This directive is just to tell Sphinx that we're documenting stuff in + """This directive is just to tell Sphinx that we're documenting stuff in namespace foo. """ @@ -639,8 +636,7 @@ class CAliasObject(ObjectDescription): } def run(self) -> list[Node]: - """ - On purpose this doesn't call the ObjectDescription version, but is based on it. + """On purpose this doesn't call the ObjectDescription version, but is based on it. Each alias signature may expand into multiple real signatures if 'noroot'. The code is therefore based on the ObjectDescription version. """ diff --git a/sphinx/domains/c/_parser.py b/sphinx/domains/c/_parser.py index bb653dfcc..7eb09f6f7 100644 --- a/sphinx/domains/c/_parser.py +++ b/sphinx/domains/c/_parser.py @@ -901,8 +901,7 @@ class DefinitionParser(BaseParser): return ASTInitializer(value) def _parse_type(self, named: bool | str, outer: str | None = None) -> ASTType: - """ - named=False|'single'|True: 'single' is e.g., for function objects which + """named=False|'single'|True: 'single' is e.g., for function objects which doesn't need to name the arguments, but otherwise is a single name """ if outer: # always named diff --git a/sphinx/domains/changeset.py b/sphinx/domains/changeset.py index 74b0bf814..2d520e6ff 100644 --- a/sphinx/domains/changeset.py +++ b/sphinx/domains/changeset.py @@ -47,9 +47,7 @@ class ChangeSet(NamedTuple): class VersionChange(SphinxDirective): - """ - Directive to describe a change/addition/deprecation in a specific version. - """ + """Directive to describe a change/addition/deprecation in a specific version.""" has_content = True required_arguments = 1 diff --git a/sphinx/domains/citation.py b/sphinx/domains/citation.py index efd8093b2..49b74cca2 100644 --- a/sphinx/domains/citation.py +++ b/sphinx/domains/citation.py @@ -148,8 +148,7 @@ class CitationDefinitionTransform(SphinxTransform): class CitationReferenceTransform(SphinxTransform): - """ - Replace citation references by pending_xref nodes before the default + """Replace citation references by pending_xref nodes before the default docutils transform tries to resolve them. """ diff --git a/sphinx/domains/cpp/__init__.py b/sphinx/domains/cpp/__init__.py index b07df32b1..d4b717624 100644 --- a/sphinx/domains/cpp/__init__.py +++ b/sphinx/domains/cpp/__init__.py @@ -528,8 +528,7 @@ class CPPEnumeratorObject(CPPObject): class CPPNamespaceObject(SphinxDirective): - """ - This directive is just to tell Sphinx that we're documenting stuff in + """This directive is just to tell Sphinx that we're documenting stuff in namespace foo. """ @@ -807,8 +806,7 @@ class CPPAliasObject(ObjectDescription): } def run(self) -> list[Node]: - """ - On purpose this doesn't call the ObjectDescription version, but is based on it. + """On purpose this doesn't call the ObjectDescription version, but is based on it. Each alias signature may expand into multiple real signatures (an overload set). The code is therefore based on the ObjectDescription version. """ diff --git a/sphinx/domains/cpp/_ids.py b/sphinx/domains/cpp/_ids.py index f7bb827bb..539fa87ad 100644 --- a/sphinx/domains/cpp/_ids.py +++ b/sphinx/domains/cpp/_ids.py @@ -1,5 +1,4 @@ -""" -Important note on ids +"""Important note on ids ---------------------------------------------------------------------------- Multiple id generation schemes are used due to backwards compatibility. diff --git a/sphinx/domains/cpp/_parser.py b/sphinx/domains/cpp/_parser.py index c88eb17cd..d28c47479 100644 --- a/sphinx/domains/cpp/_parser.py +++ b/sphinx/domains/cpp/_parser.py @@ -1624,8 +1624,7 @@ class DefinitionParser(BaseParser): return ASTInitializer(value) def _parse_type(self, named: bool | str, outer: str | None = None) -> ASTType: - """ - named=False|'maybe'|True: 'maybe' is e.g., for function objects which + """named=False|'maybe'|True: 'maybe' is e.g., for function objects which doesn't need to name the arguments outer == operatorCast: annoying case, we should not take the params diff --git a/sphinx/domains/index.py b/sphinx/domains/index.py index 9d4e8490b..f82901292 100644 --- a/sphinx/domains/index.py +++ b/sphinx/domains/index.py @@ -62,9 +62,7 @@ class IndexDomain(Domain): class IndexDirective(SphinxDirective): - """ - Directive to add entries to the index. - """ + """Directive to add entries to the index.""" has_content = False required_arguments = 1 diff --git a/sphinx/domains/javascript.py b/sphinx/domains/javascript.py index ed08d1fa6..58e35e1ad 100644 --- a/sphinx/domains/javascript.py +++ b/sphinx/domains/javascript.py @@ -35,9 +35,7 @@ logger = logging.getLogger(__name__) class JSObject(ObjectDescription[tuple[str, str]]): - """ - Description of a JavaScript object. - """ + """Description of a JavaScript object.""" #: If set to ``True`` this object is callable and a `desc_parameterlist` is #: added @@ -303,8 +301,7 @@ class JSConstructor(JSCallable): class JSModule(SphinxDirective): - """ - Directive to mark description of a new JavaScript module. + """Directive to mark description of a new JavaScript module. This directive specifies the module name that will be used by objects that follow this directive. diff --git a/sphinx/domains/python/__init__.py b/sphinx/domains/python/__init__.py index 003b468f5..5ee59fc4c 100644 --- a/sphinx/domains/python/__init__.py +++ b/sphinx/domains/python/__init__.py @@ -182,9 +182,7 @@ class PyVariable(PyObject): class PyClasslike(PyObject): - """ - Description of a class-like object (classes, interfaces, exceptions). - """ + """Description of a class-like object (classes, interfaces, exceptions).""" option_spec: ClassVar[OptionSpec] = PyObject.option_spec.copy() option_spec.update({ @@ -471,9 +469,7 @@ class PyTypeAlias(PyObject): class PyModule(SphinxDirective): - """ - Directive to mark description of a new module. - """ + """Directive to mark description of a new module.""" has_content = True required_arguments = 1 @@ -533,8 +529,7 @@ class PyModule(SphinxDirective): class PyCurrentModule(SphinxDirective): - """ - This directive is just to tell Sphinx that we're documenting + """This directive is just to tell Sphinx that we're documenting stuff in module foo, but links to module foo won't lead here. """ @@ -600,9 +595,7 @@ def filter_meta_fields( class PythonModuleIndex(Index): - """ - Index subclass to provide the Python module index. - """ + """Index subclass to provide the Python module index.""" name = 'modindex' localname = _('Python Module Index') diff --git a/sphinx/domains/python/_object.py b/sphinx/domains/python/_object.py index 5206d69e0..90cfd935d 100644 --- a/sphinx/domains/python/_object.py +++ b/sphinx/domains/python/_object.py @@ -162,8 +162,7 @@ class PyTypedField(PyXrefMixin, TypedField): class PyObject(ObjectDescription[tuple[str, str]]): - """ - Description of a general Python object. + """Description of a general Python object. :cvar allow_nesting: Class is an object that allows for nested namespaces :vartype allow_nesting: bool diff --git a/sphinx/domains/rst.py b/sphinx/domains/rst.py index af5ace5d3..1f168bc90 100644 --- a/sphinx/domains/rst.py +++ b/sphinx/domains/rst.py @@ -34,9 +34,7 @@ dir_sig_re = re.compile(r'\.\. (.+?)::(.*)$') class ReSTMarkup(ObjectDescription[str]): - """ - Description of generic reST markup. - """ + """Description of generic reST markup.""" option_spec: ClassVar[OptionSpec] = { 'no-index': directives.flag, @@ -119,9 +117,7 @@ def parse_directive(d: str) -> tuple[str, str]: class ReSTDirective(ReSTMarkup): - """ - Description of a reST directive. - """ + """Description of a reST directive.""" def handle_signature(self, sig: str, signode: desc_signature) -> str: name, args = parse_directive(sig) @@ -147,9 +143,7 @@ class ReSTDirective(ReSTMarkup): class ReSTDirectiveOption(ReSTMarkup): - """ - Description of an option for reST directive. - """ + """Description of an option for reST directive.""" option_spec: ClassVar[OptionSpec] = ReSTMarkup.option_spec.copy() option_spec.update({ @@ -219,9 +213,7 @@ class ReSTDirectiveOption(ReSTMarkup): class ReSTRole(ReSTMarkup): - """ - Description of a reST role. - """ + """Description of a reST role.""" def handle_signature(self, sig: str, signode: desc_signature) -> str: desc_name = f':{sig}:' diff --git a/sphinx/domains/std/__init__.py b/sphinx/domains/std/__init__.py index f7395dad7..987c15538 100644 --- a/sphinx/domains/std/__init__.py +++ b/sphinx/domains/std/__init__.py @@ -50,9 +50,7 @@ samp_role = EmphasizedLiteral() class GenericObject(ObjectDescription[str]): - """ - A generic x-ref directive registered with Sphinx.add_object_type(). - """ + """A generic x-ref directive registered with Sphinx.add_object_type().""" indextemplate: str = '' parse_node: Callable[[BuildEnvironment, str, desc_signature], str] | None = None @@ -93,9 +91,7 @@ class EnvVar(GenericObject): class EnvVarXRefRole(XRefRole): - """ - Cross-referencing role for environment variables (adds an index entry). - """ + """Cross-referencing role for environment variables (adds an index entry).""" def result_nodes( self, @@ -192,9 +188,7 @@ class ConfigurationValue(ObjectDescription[str]): class Target(SphinxDirective): - """ - Generic target for user-defined cross-reference types. - """ + """Generic target for user-defined cross-reference types.""" indextemplate = '' @@ -232,9 +226,7 @@ class Target(SphinxDirective): class Cmdoption(ObjectDescription[str]): - """ - Description of a command-line option (.. option). - """ + """Description of a command-line option (.. option).""" def handle_signature(self, sig: str, signode: desc_signature) -> str: """Transform an option description into RST nodes.""" @@ -338,9 +330,7 @@ class Cmdoption(ObjectDescription[str]): class Program(SphinxDirective): - """ - Directive to name the program for which options are documented. - """ + """Directive to name the program for which options are documented.""" has_content = False required_arguments = 1 @@ -417,8 +407,7 @@ def make_glossary_term( class Glossary(SphinxDirective): - """ - Directive to create a glossary with cross-reference targets for :term: + """Directive to create a glossary with cross-reference targets for :term: roles. """ @@ -599,9 +588,7 @@ def token_xrefs(text: str, *, production_group: str = '') -> list[Node]: class ProductionList(SphinxDirective): - """ - Directive to list grammar productions. - """ + """Directive to list grammar productions.""" has_content = False required_arguments = 1 @@ -666,8 +653,7 @@ class TokenXRefRole(XRefRole): class StandardDomain(Domain): - """ - Domain for all objects that don't fit into another domain or are added + """Domain for all objects that don't fit into another domain or are added via the application interface. """ diff --git a/sphinx/environment/__init__.py b/sphinx/environment/__init__.py index 04be8dbd9..88597b4a8 100644 --- a/sphinx/environment/__init__.py +++ b/sphinx/environment/__init__.py @@ -94,8 +94,7 @@ versioning_conditions: dict[str, Literal[False] | Callable[[Node], bool]] = { class BuildEnvironment: - """ - The environment in which the ReST files are translated. + """The environment in which the ReST files are translated. Stores an inventory of cross-file targets and provides doctree transformations to resolve links to them. """ diff --git a/sphinx/ext/apidoc/_generate.py b/sphinx/ext/apidoc/_generate.py index f17906d09..8c6da962a 100644 --- a/sphinx/ext/apidoc/_generate.py +++ b/sphinx/ext/apidoc/_generate.py @@ -276,8 +276,7 @@ def recurse_tree( opts: ApidocOptions, user_template_dir: str | None = None, ) -> tuple[list[Path], list[str]]: - """ - Look for every file in the directory tree and create the corresponding + """Look for every file in the directory tree and create the corresponding ReST files. """ # check if the base directory is a package and get its name diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py index 605b9a9c0..667ca4f4d 100644 --- a/sphinx/ext/autodoc/__init__.py +++ b/sphinx/ext/autodoc/__init__.py @@ -337,8 +337,7 @@ class ObjectMember: class Documenter: - """ - A Documenter knows how to autodocument a single object type. When + """A Documenter knows how to autodocument a single object type. When registered with the AutoDirective, it will be used to document objects of that type when needed by autodoc. @@ -1075,9 +1074,7 @@ class Documenter: class ModuleDocumenter(Documenter): - """ - Specialized Documenter subclass for modules. - """ + """Specialized Documenter subclass for modules.""" objtype = 'module' content_indent = '' @@ -1264,8 +1261,7 @@ class ModuleDocumenter(Documenter): class ModuleLevelDocumenter(Documenter): - """ - Specialized Documenter subclass for objects on module level (functions, + """Specialized Documenter subclass for objects on module level (functions, classes, data/constants). """ @@ -1289,8 +1285,7 @@ class ModuleLevelDocumenter(Documenter): class ClassLevelDocumenter(Documenter): - """ - Specialized Documenter subclass for objects on class level (methods, + """Specialized Documenter subclass for objects on class level (methods, attributes). """ @@ -1325,8 +1320,7 @@ class ClassLevelDocumenter(Documenter): class DocstringSignatureMixin: - """ - Mixin for FunctionDocumenter and MethodDocumenter to provide the + """Mixin for FunctionDocumenter and MethodDocumenter to provide the feature of reading the signature from the docstring. """ @@ -1407,8 +1401,7 @@ class DocstringSignatureMixin: class DocstringStripSignatureMixin(DocstringSignatureMixin): - """ - Mixin for AttributeDocumenter to provide the + """Mixin for AttributeDocumenter to provide the feature of stripping any function signature from the docstring. """ @@ -1426,9 +1419,7 @@ class DocstringStripSignatureMixin(DocstringSignatureMixin): class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type: ignore[misc] - """ - Specialized Documenter subclass for functions. - """ + """Specialized Documenter subclass for functions.""" objtype = 'function' member_order = 30 @@ -1568,9 +1559,7 @@ class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # typ class DecoratorDocumenter(FunctionDocumenter): - """ - Specialized Documenter subclass for decorator functions. - """ + """Specialized Documenter subclass for decorator functions.""" objtype = 'decorator' @@ -1600,9 +1589,7 @@ _CLASS_NEW_BLACKLIST = frozenset({ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type: ignore[misc] - """ - Specialized Documenter subclass for classes. - """ + """Specialized Documenter subclass for classes.""" objtype = 'class' member_order = 20 @@ -2098,9 +2085,7 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type: class ExceptionDocumenter(ClassDocumenter): - """ - Specialized ClassDocumenter subclass for exceptions. - """ + """Specialized ClassDocumenter subclass for exceptions.""" objtype = 'exception' member_order = 10 @@ -2148,8 +2133,7 @@ class DataDocumenterMixinBase: class GenericAliasMixin(DataDocumenterMixinBase): - """ - Mixin for DataDocumenter and AttributeDocumenter to provide the feature for + """Mixin for DataDocumenter and AttributeDocumenter to provide the feature for supporting GenericAliases. """ @@ -2173,8 +2157,7 @@ class GenericAliasMixin(DataDocumenterMixinBase): class UninitializedGlobalVariableMixin(DataDocumenterMixinBase): - """ - Mixin for DataDocumenter to provide the feature for supporting uninitialized + """Mixin for DataDocumenter to provide the feature for supporting uninitialized (type annotation only) global variables. """ @@ -2220,9 +2203,7 @@ class UninitializedGlobalVariableMixin(DataDocumenterMixinBase): class DataDocumenter( GenericAliasMixin, UninitializedGlobalVariableMixin, ModuleLevelDocumenter ): - """ - Specialized Documenter subclass for data items. - """ + """Specialized Documenter subclass for data items.""" objtype = 'data' member_order = 40 @@ -2355,9 +2336,7 @@ class DataDocumenter( class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type: ignore[misc] - """ - Specialized Documenter subclass for methods (normal, static and class). - """ + """Specialized Documenter subclass for methods (normal, static and class).""" objtype = 'method' directivetype = 'method' @@ -2616,8 +2595,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type: class NonDataDescriptorMixin(DataDocumenterMixinBase): - """ - Mixin for AttributeDocumenter to provide the feature for supporting non + """Mixin for AttributeDocumenter to provide the feature for supporting non data-descriptors. .. note:: This mix-in must be inherited after other mix-ins. Otherwise, docstring @@ -2649,9 +2627,7 @@ class NonDataDescriptorMixin(DataDocumenterMixinBase): class SlotsMixin(DataDocumenterMixinBase): - """ - Mixin for AttributeDocumenter to provide the feature for supporting __slots__. - """ + """Mixin for AttributeDocumenter to provide the feature for supporting __slots__.""" def isslotsattribute(self) -> bool: """Check the subject is an attribute in __slots__.""" @@ -2699,11 +2675,10 @@ class SlotsMixin(DataDocumenterMixinBase): class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase): - """ - Mixin for AttributeDocumenter to provide the feature for supporting runtime + """Mixin for AttributeDocumenter to provide the feature for supporting runtime instance attributes (that are defined in __init__() methods with doc-comments). - Example: + Example:: class Foo: def __init__(self): @@ -2783,11 +2758,10 @@ class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase): class UninitializedInstanceAttributeMixin(DataDocumenterMixinBase): - """ - Mixin for AttributeDocumenter to provide the feature for supporting uninitialized + """Mixin for AttributeDocumenter to provide the feature for supporting uninitialized instance attributes (PEP-526 styled, annotation only attributes). - Example: + Example:: class Foo: attr: int #: This is a target of this mix-in. @@ -2848,9 +2822,7 @@ class AttributeDocumenter( # type: ignore[misc] DocstringStripSignatureMixin, ClassLevelDocumenter, ): - """ - Specialized Documenter subclass for attributes. - """ + """Specialized Documenter subclass for attributes.""" objtype = 'attribute' member_order = 60 @@ -3020,9 +2992,7 @@ class AttributeDocumenter( # type: ignore[misc] class PropertyDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter): # type: ignore[misc] - """ - Specialized Documenter subclass for properties. - """ + """Specialized Documenter subclass for properties.""" objtype = 'property' member_order = 60 diff --git a/sphinx/ext/autodoc/importer.py b/sphinx/ext/autodoc/importer.py index 54304cf1d..ab12df510 100644 --- a/sphinx/ext/autodoc/importer.py +++ b/sphinx/ext/autodoc/importer.py @@ -161,9 +161,7 @@ def import_module(modname: str) -> Any: def _reload_module(module: ModuleType) -> Any: - """ - Call importlib.reload(module), convert exceptions to ImportError - """ + """Call importlib.reload(module), convert exceptions to ImportError""" try: return importlib.reload(module) except BaseException as exc: diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py index 495ec3189..23efcc88c 100644 --- a/sphinx/ext/autosummary/__init__.py +++ b/sphinx/ext/autosummary/__init__.py @@ -224,8 +224,7 @@ def get_documenter(app: Sphinx, obj: Any, parent: Any) -> type[Documenter]: class Autosummary(SphinxDirective): - """ - Pretty table containing short signatures and summaries of functions etc. + """Pretty table containing short signatures and summaries of functions etc. autosummary can also optionally generate a hidden toctree:: node. """ @@ -660,8 +659,7 @@ class ImportExceptionGroup(Exception): def get_import_prefixes_from_env(env: BuildEnvironment) -> list[str | None]: - """ - Obtain current Python import prefixes (for `import_by_name`) + """Obtain current Python import prefixes (for `import_by_name`) from ``document.env`` """ prefixes: list[str | None] = [None] diff --git a/sphinx/ext/coverage.py b/sphinx/ext/coverage.py index 840f86c4b..a7c6c6538 100644 --- a/sphinx/ext/coverage.py +++ b/sphinx/ext/coverage.py @@ -165,9 +165,7 @@ def _determine_py_coverage_modules( class CoverageBuilder(Builder): - """ - Evaluates coverage of code in the documentation. - """ + """Evaluates coverage of code in the documentation.""" name = 'coverage' epilog = __( diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py index f69a19223..5e4b38310 100644 --- a/sphinx/ext/doctest.py +++ b/sphinx/ext/doctest.py @@ -64,9 +64,7 @@ def is_allowed_version(spec: str, version: str) -> bool: class TestDirective(SphinxDirective): - """ - Base class for doctest-related directives. - """ + """Base class for doctest-related directives.""" has_content = True required_arguments = 0 @@ -292,9 +290,7 @@ class SphinxDocTestRunner(doctest.DocTestRunner): class DocTestBuilder(Builder): - """ - Runs test snippets in the documentation. - """ + """Runs test snippets in the documentation.""" name = 'doctest' epilog = __( diff --git a/sphinx/ext/extlinks.py b/sphinx/ext/extlinks.py index 51e91562c..2d5ac096f 100644 --- a/sphinx/ext/extlinks.py +++ b/sphinx/ext/extlinks.py @@ -44,8 +44,7 @@ logger = logging.getLogger(__name__) class ExternalLinksChecker(SphinxPostTransform): - """ - For each external link, check if it can be replaced by an extlink. + """For each external link, check if it can be replaced by an extlink. We treat each ``reference`` node without ``internal`` attribute as an external link. """ @@ -60,8 +59,7 @@ class ExternalLinksChecker(SphinxPostTransform): self.check_uri(refnode) def check_uri(self, refnode: nodes.reference) -> None: - """ - If the URI in ``refnode`` has a replacement in ``extlinks``, + """If the URI in ``refnode`` has a replacement in ``extlinks``, emit a warning with a replacement suggestion. """ if 'internal' in refnode or 'refuri' not in refnode: diff --git a/sphinx/ext/graphviz.py b/sphinx/ext/graphviz.py index 77a0a9a9e..107872e47 100644 --- a/sphinx/ext/graphviz.py +++ b/sphinx/ext/graphviz.py @@ -113,9 +113,7 @@ def align_spec(argument: Any) -> str: class Graphviz(SphinxDirective): - """ - Directive to insert arbitrary dot markup. - """ + """Directive to insert arbitrary dot markup.""" has_content = True required_arguments = 0 @@ -195,9 +193,7 @@ class Graphviz(SphinxDirective): class GraphvizSimple(SphinxDirective): - """ - Directive to insert arbitrary dot markup. - """ + """Directive to insert arbitrary dot markup.""" has_content = True required_arguments = 1 diff --git a/sphinx/ext/inheritance_diagram.py b/sphinx/ext/inheritance_diagram.py index 68b463d9b..69140cf20 100644 --- a/sphinx/ext/inheritance_diagram.py +++ b/sphinx/ext/inheritance_diagram.py @@ -143,8 +143,7 @@ class InheritanceException(Exception): class InheritanceGraph: - """ - Given a list of classes, determines the set of classes that they inherit + """Given a list of classes, determines the set of classes that they inherit from all the way to the root "object", and then is able to generate a graphviz dot graph from them. """ @@ -361,17 +360,13 @@ class InheritanceGraph: class inheritance_diagram(graphviz): - """ - A docutils node to use as a placeholder for the inheritance diagram. - """ + """A docutils node to use as a placeholder for the inheritance diagram.""" pass class InheritanceDiagram(SphinxDirective): - """ - Run when the inheritance_diagram directive is first encountered. - """ + """Run when the inheritance_diagram directive is first encountered.""" has_content = False required_arguments = 1 @@ -441,8 +436,7 @@ def get_graph_hash(node: inheritance_diagram) -> str: def html_visit_inheritance_diagram( self: HTML5Translator, node: inheritance_diagram ) -> None: - """ - Output the graph for HTML. This will insert a PNG with clickable + """Output the graph for HTML. This will insert a PNG with clickable image map. """ graph = node['graph'] @@ -488,9 +482,7 @@ def html_visit_inheritance_diagram( def latex_visit_inheritance_diagram( self: LaTeXTranslator, node: inheritance_diagram ) -> None: - """ - Output the graph for LaTeX. This will insert a PDF. - """ + """Output the graph for LaTeX. This will insert a PDF.""" graph = node['graph'] graph_hash = get_graph_hash(node) @@ -507,9 +499,7 @@ def texinfo_visit_inheritance_diagram( self: TexinfoTranslator, node: inheritance_diagram, ) -> None: - """ - Output the graph for Texinfo. This will insert a PNG. - """ + """Output the graph for Texinfo. This will insert a PNG.""" graph = node['graph'] graph_hash = get_graph_hash(node) diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py index 90a5bf57c..1a3ffd8bd 100644 --- a/sphinx/ext/napoleon/docstring.py +++ b/sphinx/ext/napoleon/docstring.py @@ -55,8 +55,7 @@ _SINGLETONS = frozenset({'None', 'True', 'False', 'Ellipsis', '...'}) class Deque(collections.deque[Any]): - """ - A subclass of deque that mimics ``pockets.iterators.modify_iter``. + """A subclass of deque that mimics ``pockets.iterators.modify_iter``. The `.Deque.get` and `.Deque.next` methods are added. """ @@ -64,8 +63,7 @@ class Deque(collections.deque[Any]): sentinel = object() def get(self, n: int) -> Any: - """ - Return the nth element of the stack, or ``self.sentinel`` if n is + """Return the nth element of the stack, or ``self.sentinel`` if n is greater than the stack size. """ return self[n] if n < len(self) else self.sentinel @@ -1293,8 +1291,7 @@ class NumpyDocstring(GoogleDocstring): return self._format_admonition('seealso', lines) def _parse_numpydoc_see_also_section(self, content: list[str]) -> list[str]: - """ - See Also + """See Also -------- func_name : Descriptive text continued text diff --git a/sphinx/ext/todo.py b/sphinx/ext/todo.py index 9e0768d29..0e192dbda 100644 --- a/sphinx/ext/todo.py +++ b/sphinx/ext/todo.py @@ -47,9 +47,7 @@ class todolist(nodes.General, nodes.Element): class Todo(BaseAdmonition, SphinxDirective): - """ - A todo entry, displayed (if configured) in the form of an admonition. - """ + """A todo entry, displayed (if configured) in the form of an admonition.""" node_class = todo_node has_content = True @@ -109,9 +107,7 @@ class TodoDomain(Domain): class TodoList(SphinxDirective): - """ - A list of all todo entries. - """ + """A list of all todo entries.""" has_content = False required_arguments = 0 diff --git a/sphinx/io.py b/sphinx/io.py index 9df94f3a5..cedd1a20c 100644 --- a/sphinx/io.py +++ b/sphinx/io.py @@ -39,8 +39,7 @@ logger = logging.getLogger(__name__) class SphinxBaseReader(standalone.Reader): # type: ignore[misc] - """ - A base class of readers for Sphinx. + """A base class of readers for Sphinx. This replaces reporter by Sphinx's on generating document. """ @@ -73,8 +72,7 @@ class SphinxBaseReader(standalone.Reader): # type: ignore[misc] return transforms def new_document(self) -> nodes.document: - """ - Creates a new document object which has a special reporter object good + """Creates a new document object which has a special reporter object good for logging. """ document = super().new_document() @@ -92,9 +90,7 @@ class SphinxBaseReader(standalone.Reader): # type: ignore[misc] class SphinxStandaloneReader(SphinxBaseReader): - """ - A basic document reader for Sphinx. - """ + """A basic document reader for Sphinx.""" def setup(self, app: Sphinx) -> None: self.transforms = self.transforms + app.registry.get_transforms() @@ -120,8 +116,7 @@ class SphinxStandaloneReader(SphinxBaseReader): class SphinxI18nReader(SphinxBaseReader): - """ - A document reader for i18n. + """A document reader for i18n. This returns the source line number of original text as current source line number to let users know where the error happened. diff --git a/sphinx/jinja2glue.py b/sphinx/jinja2glue.py index 5a42c117c..e67c1b95d 100644 --- a/sphinx/jinja2glue.py +++ b/sphinx/jinja2glue.py @@ -41,8 +41,7 @@ def _toint(val: str) -> int: def _todim(val: int | str) -> str: - """ - Make val a css dimension. In particular the following transformations + """Make val a css dimension. In particular the following transformations are performed: - None -> 'initial' (default CSS value) @@ -114,8 +113,7 @@ def warning(context: dict[str, Any], message: str, *args: Any, **kwargs: Any) -> class SphinxFileSystemLoader(FileSystemLoader): - """ - FileSystemLoader subclass that is not so strict about '..' entries in + """FileSystemLoader subclass that is not so strict about '..' entries in template names. """ @@ -156,9 +154,7 @@ class SphinxFileSystemLoader(FileSystemLoader): class BuiltinTemplateLoader(TemplateBridge, BaseLoader): - """ - Interfaces the rendering environment of jinja2 for use in Sphinx. - """ + """Interfaces the rendering environment of jinja2 for use in Sphinx.""" # TemplateBridge interface diff --git a/sphinx/locale/__init__.py b/sphinx/locale/__init__.py index 0fce1dd5d..7465864d9 100644 --- a/sphinx/locale/__init__.py +++ b/sphinx/locale/__init__.py @@ -15,8 +15,7 @@ if TYPE_CHECKING: class _TranslationProxy: - """ - The proxy implementation attempts to be as complete as possible, so that + """The proxy implementation attempts to be as complete as possible, so that the lazy objects should mostly work as expected, for example for sorting. """ diff --git a/sphinx/parsers.py b/sphinx/parsers.py index 814f0b988..70ff3eaae 100644 --- a/sphinx/parsers.py +++ b/sphinx/parsers.py @@ -23,10 +23,12 @@ if TYPE_CHECKING: class Parser(docutils.parsers.Parser): - """ - A base class of source parsers. The additional parsers should inherit this class instead - of ``docutils.parsers.Parser``. Compared with ``docutils.parsers.Parser``, this class - improves accessibility to Sphinx APIs. + """A base class of source parsers. + + The additional parsers should inherit this class + instead of ``docutils.parsers.Parser``. + Compared with ``docutils.parsers.Parser``, + this class improves accessibility to Sphinx APIs. The subclasses can access sphinx core runtime objects (app, config and env). """ @@ -51,8 +53,7 @@ class RSTParser(docutils.parsers.rst.Parser, Parser): """A reST parser for Sphinx.""" def get_transforms(self) -> list[type[Transform]]: - """ - Sphinx's reST parser replaces a transform class for smart-quotes by its own + """Sphinx's reST parser replaces a transform class for smart-quotes by its own refs: sphinx.io.SphinxStandaloneReader """ diff --git a/sphinx/pygments_styles.py b/sphinx/pygments_styles.py index 57924664f..a6eabcb24 100644 --- a/sphinx/pygments_styles.py +++ b/sphinx/pygments_styles.py @@ -22,8 +22,7 @@ class NoneStyle(Style): class SphinxStyle(Style): - """ - Like friendly, but a bit darker to enhance contrast on the green + """Like friendly, but a bit darker to enhance contrast on the green background. """ @@ -39,9 +38,7 @@ class SphinxStyle(Style): class PyramidStyle(Style): - """ - Pylons/pyramid pygments style based on friendly style, by Blaise Laflamme. - """ + """Pylons/pyramid pygments style based on friendly style, by Blaise Laflamme.""" # work in progress... diff --git a/sphinx/roles.py b/sphinx/roles.py index 568a212e7..98843de5a 100644 --- a/sphinx/roles.py +++ b/sphinx/roles.py @@ -42,8 +42,7 @@ generic_docroles = { class XRefRole(ReferenceRole): - """ - A generic cross-referencing role. To create a callable that can be used as + """A generic cross-referencing role. To create a callable that can be used as a role function, create an instance of this class. The general features of this role are: @@ -370,8 +369,7 @@ class RFC(ReferenceRole): def _format_rfc_target(target: str, /) -> str: - """ - Takes an RFC number with an optional anchor (like ``123#section-2.5.3``) + """Takes an RFC number with an optional anchor (like ``123#section-2.5.3``) and attempts to produce a human-friendly title for it. We have a set of known anchors that we format nicely, diff --git a/sphinx/search/__init__.py b/sphinx/search/__init__.py index 39516e2cf..0093b76be 100644 --- a/sphinx/search/__init__.py +++ b/sphinx/search/__init__.py @@ -33,8 +33,7 @@ _MINIFIED_JS_PATH = Path(package_dir, 'search', 'minified-js') class SearchLanguage: - """ - This class is the base class for search natural language preprocessors. If + """This class is the base class for search natural language preprocessors. If you want to add support for a new language, you should override the methods of this class. @@ -86,21 +85,17 @@ var Stemmer = function() { self.init(options) def init(self, options: dict[str, str]) -> None: - """ - Initialize the class with the options the user has given. - """ + """Initialize the class with the options the user has given.""" def split(self, input: str) -> list[str]: - """ - This method splits a sentence into words. Default splitter splits input + """This method splits a sentence into words. Default splitter splits input at white spaces, which should be enough for most languages except CJK languages. """ return self._word_re.findall(input) def stem(self, word: str) -> str: - """ - This method implements stemming algorithm of the Python version. + """This method implements stemming algorithm of the Python version. Default implementation does nothing. You should implement this if the language has any stemming rules. @@ -112,8 +107,7 @@ var Stemmer = function() { return word def word_filter(self, word: str) -> bool: - """ - Return true if the target word should be registered in the search index. + """Return true if the target word should be registered in the search index. This method is called after stemming. """ return len(word) == 0 or not ( @@ -127,8 +121,7 @@ from sphinx.search.en import SearchEnglish # NoQA: E402 def parse_stop_word(source: str) -> set[str]: - """ - Parse snowball style word list like this: + """Parse snowball style word list like this: * https://snowball.tartarus.org/algorithms/finnish/stop.txt """ @@ -162,8 +155,7 @@ languages: dict[str, str | type[SearchLanguage]] = { class _JavaScriptIndex: - """ - The search index as JavaScript file that calls a function + """The search index as JavaScript file that calls a function on the documentation search object to register the index. """ @@ -212,9 +204,7 @@ class WordStore: class WordCollector(nodes.NodeVisitor): - """ - A special visitor that collects words for the `IndexBuilder`. - """ + """A special visitor that collects words for the `IndexBuilder`.""" def __init__(self, document: nodes.document, lang: SearchLanguage) -> None: super().__init__(document) @@ -262,8 +252,7 @@ class WordCollector(nodes.NodeVisitor): class IndexBuilder: - """ - Helper class that creates a search index based on the doctrees + """Helper class that creates a search index based on the doctrees passed to the `feed` method. """ diff --git a/sphinx/search/ja.py b/sphinx/search/ja.py index a51053066..9d6df1fe1 100644 --- a/sphinx/search/ja.py +++ b/sphinx/search/ja.py @@ -42,8 +42,7 @@ class BaseSplitter: self.options = options def split(self, input: str) -> list[str]: - """ - :param str input: + """:param str input: :return: :rtype: list[str] """ @@ -516,8 +515,7 @@ class DefaultSplitter(BaseSplitter): class SearchJapanese(SearchLanguage): - """ - Japanese search implementation: uses no stemmer, but word splitting is quite + """Japanese search implementation: uses no stemmer, but word splitting is quite complicated. """ diff --git a/sphinx/search/zh.py b/sphinx/search/zh.py index 59c575b4a..a63b6d63a 100644 --- a/sphinx/search/zh.py +++ b/sphinx/search/zh.py @@ -218,9 +218,7 @@ iti|ous|ive|ize)$/; class SearchChinese(SearchLanguage): - """ - Chinese search implementation - """ + """Chinese search implementation""" lang = 'zh' language_name = 'Chinese' diff --git a/sphinx/testing/fixtures.py b/sphinx/testing/fixtures.py index 2e09c1ea8..4b4766be0 100644 --- a/sphinx/testing/fixtures.py +++ b/sphinx/testing/fixtures.py @@ -76,8 +76,7 @@ def app_params( sphinx_test_tempdir: str, rootdir: Path, ) -> _app_params: - """ - Parameters that are specified by 'pytest.mark.sphinx' for + """Parameters that are specified by 'pytest.mark.sphinx' for sphinx.application.Sphinx initialization """ # ##### process pytest.mark.sphinx @@ -119,8 +118,7 @@ _app_params = namedtuple('_app_params', 'args,kwargs') # NoQA: PYI024 @pytest.fixture def test_params(request: Any) -> dict[str, Any]: - """ - Test parameters that are specified by 'pytest.mark.test_params' + """Test parameters that are specified by 'pytest.mark.test_params' :param Union[str] shared_result: If the value is provided, app._status and app._warning objects will be @@ -148,9 +146,7 @@ def app( make_app: Callable[[], SphinxTestApp], shared_result: SharedResult, ) -> Iterator[SphinxTestApp]: - """ - Provides the 'sphinx.application.Sphinx' object - """ + """Provides the 'sphinx.application.Sphinx' object""" args, kwargs = app_params app_ = make_app(*args, **kwargs) yield app_ @@ -168,24 +164,19 @@ def app( @pytest.fixture def status(app: SphinxTestApp) -> StringIO: - """ - Back-compatibility for testing with previous @with_app decorator - """ + """Back-compatibility for testing with previous @with_app decorator""" return app.status @pytest.fixture def warning(app: SphinxTestApp) -> StringIO: - """ - Back-compatibility for testing with previous @with_app decorator - """ + """Back-compatibility for testing with previous @with_app decorator""" return app.warning @pytest.fixture def make_app(test_params: dict[str, Any]) -> Iterator[Callable[[], SphinxTestApp]]: - """ - Provides make_app function to initialize SphinxTestApp instance. + """Provides make_app function to initialize SphinxTestApp instance. if you want to initialize 'app' in your test function. please use this instead of using SphinxTestApp class directory. """ @@ -223,8 +214,7 @@ def _shared_result_cache() -> None: @pytest.fixture def if_graphviz_found(app: SphinxTestApp) -> None: - """ - The test will be skipped when using 'if_graphviz_found' fixture and graphviz + """The test will be skipped when using 'if_graphviz_found' fixture and graphviz dot command is not found. """ graphviz_dot = getattr(app.config, 'graphviz_dot', '') @@ -247,8 +237,7 @@ def sphinx_test_tempdir(tmp_path_factory: pytest.TempPathFactory) -> Path: @pytest.fixture def rollback_sysmodules() -> Iterator[None]: - """ - Rollback sys.modules to its value before testing to unload modules + """Rollback sys.modules to its value before testing to unload modules during tests. For example, used in test_ext_autosummary.py to permit unloading the diff --git a/sphinx/testing/path.py b/sphinx/testing/path.py index e05936a15..2d01f9350 100644 --- a/sphinx/testing/path.py +++ b/sphinx/testing/path.py @@ -34,56 +34,40 @@ UMASK = getumask() class path(str): # NoQA: FURB189 - """ - Represents a path which behaves like a string. - """ + """Represents a path which behaves like a string.""" __slots__ = () @property def parent(self) -> path: - """ - The name of the directory the file or directory is in. - """ + """The name of the directory the file or directory is in.""" return self.__class__(os.path.dirname(self)) def basename(self) -> str: return os.path.basename(self) def abspath(self) -> path: - """ - Returns the absolute path. - """ + """Returns the absolute path.""" return self.__class__(os.path.abspath(self)) def isabs(self) -> bool: - """ - Returns ``True`` if the path is absolute. - """ + """Returns ``True`` if the path is absolute.""" return os.path.isabs(self) def isdir(self) -> bool: - """ - Returns ``True`` if the path is a directory. - """ + """Returns ``True`` if the path is a directory.""" return os.path.isdir(self) def isfile(self) -> bool: - """ - Returns ``True`` if the path is a file. - """ + """Returns ``True`` if the path is a file.""" return os.path.isfile(self) def islink(self) -> bool: - """ - Returns ``True`` if the path is a symbolic link. - """ + """Returns ``True`` if the path is a symbolic link.""" return os.path.islink(self) def ismount(self) -> bool: - """ - Returns ``True`` if the path is a mount point. - """ + """Returns ``True`` if the path is a mount point.""" return os.path.ismount(self) def rmtree( @@ -91,8 +75,7 @@ class path(str): # NoQA: FURB189 ignore_errors: bool = False, onerror: Callable[[Callable[..., Any], str, Any], object] | None = None, ) -> None: - """ - Removes the file or directory and any files or directories it may + """Removes the file or directory and any files or directories it may contain. :param ignore_errors: @@ -109,8 +92,7 @@ class path(str): # NoQA: FURB189 shutil.rmtree(self, ignore_errors=ignore_errors, onerror=onerror) def copytree(self, destination: str, symlinks: bool = False) -> None: - """ - Recursively copy a directory to the given `destination`. If the given + """Recursively copy a directory to the given `destination`. If the given `destination` does not exist it will be created. :param symlinks: @@ -131,8 +113,7 @@ class path(str): # NoQA: FURB189 os.chmod(os.path.join(root, name), 0o644 & ~UMASK) def movetree(self, destination: str) -> None: - """ - Recursively move the file or directory to the given `destination` + """Recursively move the file or directory to the given `destination` similar to the Unix "mv" command. If the `destination` is a file it may be overwritten depending on the @@ -143,15 +124,11 @@ class path(str): # NoQA: FURB189 move = movetree def unlink(self) -> None: - """ - Removes a file. - """ + """Removes a file.""" os.unlink(self) def stat(self) -> Any: - """ - Returns a stat of the file. - """ + """Returns a stat of the file.""" return os.stat(self) def utime(self, arg: Any) -> None: @@ -161,29 +138,22 @@ class path(str): # NoQA: FURB189 return open(self, mode, **kwargs) def write_text(self, text: str, encoding: str = 'utf-8', **kwargs: Any) -> None: - """ - Writes the given `text` to the file. - """ + """Writes the given `text` to the file.""" with open(self, 'w', encoding=encoding, **kwargs) as f: f.write(text) def read_text(self, encoding: str = 'utf-8', **kwargs: Any) -> str: - """ - Returns the text in the file. - """ + """Returns the text in the file.""" with open(self, encoding=encoding, **kwargs) as f: return f.read() def read_bytes(self) -> builtins.bytes: - """ - Returns the bytes in the file. - """ + """Returns the bytes in the file.""" with open(self, mode='rb') as f: return f.read() def write_bytes(self, bytes: bytes, append: bool = False) -> None: - """ - Writes the given `bytes` to the file. + """Writes the given `bytes` to the file. :param append: If ``True`` given `bytes` are added at the end of the file. @@ -196,28 +166,21 @@ class path(str): # NoQA: FURB189 f.write(bytes) def exists(self) -> bool: - """ - Returns ``True`` if the path exist. - """ + """Returns ``True`` if the path exist.""" return os.path.exists(self) def lexists(self) -> bool: - """ - Returns ``True`` if the path exists unless it is a broken symbolic + """Returns ``True`` if the path exists unless it is a broken symbolic link. """ return os.path.lexists(self) def makedirs(self, mode: int = 0o777, exist_ok: bool = False) -> None: - """ - Recursively create directories. - """ + """Recursively create directories.""" os.makedirs(self, mode, exist_ok=exist_ok) def joinpath(self, *args: Any) -> path: - """ - Joins the path with the argument given and returns the result. - """ + """Joins the path with the argument given and returns the result.""" return self.__class__(os.path.join(self, *map(self.__class__, args))) def listdir(self) -> list[str]: diff --git a/sphinx/transforms/__init__.py b/sphinx/transforms/__init__.py index e9e80f073..8724ad12a 100644 --- a/sphinx/transforms/__init__.py +++ b/sphinx/transforms/__init__.py @@ -76,9 +76,7 @@ class SphinxTransform(Transform): class SphinxTransformer(Transformer): - """ - A transformer for Sphinx. - """ + """A transformer for Sphinx.""" document: nodes.document env: BuildEnvironment | None = None @@ -106,9 +104,7 @@ class SphinxTransformer(Transformer): class DefaultSubstitutions(SphinxTransform): - """ - Replace some substitutions if they aren't defined in the document. - """ + """Replace some substitutions if they aren't defined in the document.""" # run before the default Substitutions default_priority = 210 @@ -150,8 +146,7 @@ def _calculate_translation_progress(document: nodes.document) -> str: class MoveModuleTargets(SphinxTransform): - """ - Move module targets that are the first thing in a section to the section + """Move module targets that are the first thing in a section to the section title. XXX Python specific @@ -176,9 +171,7 @@ class MoveModuleTargets(SphinxTransform): class HandleCodeBlocks(SphinxTransform): - """ - Several code block related transformations. - """ + """Several code block related transformations.""" default_priority = 210 @@ -200,9 +193,7 @@ class HandleCodeBlocks(SphinxTransform): class AutoNumbering(SphinxTransform): - """ - Register IDs of tables, figures and literal_blocks to assign numbers. - """ + """Register IDs of tables, figures and literal_blocks to assign numbers.""" default_priority = 210 @@ -219,9 +210,7 @@ class AutoNumbering(SphinxTransform): class SortIds(SphinxTransform): - """ - Sort section IDs so that the "id[0-9]+" one comes last. - """ + """Sort section IDs so that the "id[0-9]+" one comes last.""" default_priority = 261 @@ -241,9 +230,7 @@ TRANSLATABLE_NODES = { class ApplySourceWorkaround(SphinxTransform): - """ - Update source and rawsource attributes - """ + """Update source and rawsource attributes""" default_priority = 10 @@ -254,9 +241,7 @@ class ApplySourceWorkaround(SphinxTransform): class AutoIndexUpgrader(SphinxTransform): - """ - Detect old style (4 column based indices) and automatically upgrade to new style. - """ + """Detect old style (4 column based indices) and automatically upgrade to new style.""" default_priority = 210 @@ -277,9 +262,7 @@ class AutoIndexUpgrader(SphinxTransform): class ExtraTranslatableNodes(SphinxTransform): - """ - Make nodes translatable - """ + """Make nodes translatable""" default_priority = 10 @@ -297,9 +280,7 @@ class ExtraTranslatableNodes(SphinxTransform): class UnreferencedFootnotesDetector(SphinxTransform): - """ - Detect unreferenced footnotes and emit warnings - """ + """Detect unreferenced footnotes and emit warnings""" default_priority = Footnotes.default_priority + 2 @@ -361,8 +342,7 @@ class FilterSystemMessages(SphinxTransform): class SphinxContentsFilter(ContentsFilter): - """ - Used with BuildEnvironment.add_toc_from() to discard cross-file links + """Used with BuildEnvironment.add_toc_from() to discard cross-file links within table-of-contents link nodes. """ @@ -373,8 +353,7 @@ class SphinxContentsFilter(ContentsFilter): class SphinxSmartQuotes(SmartQuotes, SphinxTransform): - """ - Customized SmartQuotes to avoid transform for some extra node types. + """Customized SmartQuotes to avoid transform for some extra node types. refs: sphinx.parsers.RSTParser """ diff --git a/sphinx/transforms/i18n.py b/sphinx/transforms/i18n.py index 31542e81e..815ca606b 100644 --- a/sphinx/transforms/i18n.py +++ b/sphinx/transforms/i18n.py @@ -100,9 +100,7 @@ def parse_noqa(source: str) -> tuple[str, bool]: class PreserveTranslatableMessages(SphinxTransform): - """ - Preserve original translatable messages before translation - """ + """Preserve original translatable messages before translation""" default_priority = 10 # this MUST be invoked before Locale transform @@ -380,9 +378,7 @@ class _NodeUpdater: class Locale(SphinxTransform): - """ - Replace translatable nodes with their translated doctree. - """ + """Replace translatable nodes with their translated doctree.""" default_priority = 20 @@ -609,9 +605,7 @@ class Locale(SphinxTransform): class TranslationProgressTotaliser(SphinxTransform): - """ - Calculate the number of translated and untranslated nodes. - """ + """Calculate the number of translated and untranslated nodes.""" default_priority = 25 # MUST happen after Locale @@ -634,9 +628,7 @@ class TranslationProgressTotaliser(SphinxTransform): class AddTranslationClasses(SphinxTransform): - """ - Add ``translated`` or ``untranslated`` classes to indicate translation status. - """ + """Add ``translated`` or ``untranslated`` classes to indicate translation status.""" default_priority = 950 @@ -674,9 +666,7 @@ class AddTranslationClasses(SphinxTransform): class RemoveTranslatableInline(SphinxTransform): - """ - Remove inline nodes used for translation as placeholders. - """ + """Remove inline nodes used for translation as placeholders.""" default_priority = 999 diff --git a/sphinx/transforms/post_transforms/__init__.py b/sphinx/transforms/post_transforms/__init__.py index 74df38d40..94e425b7b 100644 --- a/sphinx/transforms/post_transforms/__init__.py +++ b/sphinx/transforms/post_transforms/__init__.py @@ -60,9 +60,7 @@ class SphinxPostTransform(SphinxTransform): class ReferencesResolver(SphinxPostTransform): - """ - Resolves cross-references on doctrees. - """ + """Resolves cross-references on doctrees.""" default_priority = 10 diff --git a/sphinx/transforms/post_transforms/code.py b/sphinx/transforms/post_transforms/code.py index 2682af29c..2d89bc65a 100644 --- a/sphinx/transforms/post_transforms/code.py +++ b/sphinx/transforms/post_transforms/code.py @@ -28,8 +28,7 @@ class HighlightSetting(NamedTuple): class HighlightLanguageTransform(SphinxTransform): - """ - Apply highlight_language to all literal_block nodes. + """Apply highlight_language to all literal_block nodes. This refers both :confval:`highlight_language` setting and :rst:dir:`highlight` directive. After processing, this transform @@ -88,8 +87,7 @@ class HighlightLanguageVisitor(nodes.NodeVisitor): class TrimDoctestFlagsTransform(SphinxTransform): - """ - Trim doctest flags like ``# doctest: +FLAG`` from python code-blocks. + """Trim doctest flags like ``# doctest: +FLAG`` from python code-blocks. see :confval:`trim_doctest_flags` for more information. """ diff --git a/sphinx/util/_files.py b/sphinx/util/_files.py index ef09c606d..0d351d8af 100644 --- a/sphinx/util/_files.py +++ b/sphinx/util/_files.py @@ -10,8 +10,7 @@ if TYPE_CHECKING: class FilenameUniqDict(dict[str, tuple[set[str], str]]): - """ - A dictionary that automatically generates unique names for its keys, + """A dictionary that automatically generates unique names for its keys, interpreted as filenames, and keeps track of a set of docnames they appear in. Used for images and downloadable files in the environment. """ diff --git a/sphinx/util/docfields.py b/sphinx/util/docfields.py index 7ee4e8d1d..093b163d9 100644 --- a/sphinx/util/docfields.py +++ b/sphinx/util/docfields.py @@ -183,8 +183,7 @@ class Field: class GroupedField(Field): - """ - A doc field that is grouped; i.e., all fields of that type will be + """A doc field that is grouped; i.e., all fields of that type will be transformed into one field with its body being a bulleted list. It always has an argument. The argument can be linked using the given *rolename*. GroupedField should be used for doc fields that can occur more than once. @@ -248,8 +247,7 @@ class GroupedField(Field): class TypedField(GroupedField): - """ - A doc field that is grouped and has type information for the arguments. It + """A doc field that is grouped and has type information for the arguments. It always has an argument. The argument can be linked using the given *rolename*, the type using the given *typerolename*. @@ -340,8 +338,7 @@ class TypedField(GroupedField): class DocFieldTransformer: - """ - Transforms field lists in "doc field" syntax into better-looking + """Transforms field lists in "doc field" syntax into better-looking equivalents, using the field type definitions given on a domain. """ diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py index 108ac63b3..efa20c735 100644 --- a/sphinx/util/docutils.py +++ b/sphinx/util/docutils.py @@ -730,8 +730,7 @@ class SphinxTranslator(nodes.NodeVisitor): self._domains = builder.env.domains def dispatch_visit(self, node: Node) -> None: - """ - Dispatch node to appropriate visitor method. + """Dispatch node to appropriate visitor method. The priority of visitor method is: 1. ``self.visit_{node_class}()`` @@ -747,8 +746,7 @@ class SphinxTranslator(nodes.NodeVisitor): super().dispatch_visit(node) def dispatch_departure(self, node: Node) -> None: - """ - Dispatch node to appropriate departure method. + """Dispatch node to appropriate departure method. The priority of departure method is: 1. ``self.depart_{node_class}()`` diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py index ec7bf4fc5..aaa10e09d 100644 --- a/sphinx/util/nodes.py +++ b/sphinx/util/nodes.py @@ -99,8 +99,7 @@ class NodeMatcher(Generic[N]): def get_full_module_name(node: Node) -> str: - """ - Return full module dotted path like: 'docutils.nodes.paragraph' + """Return full module dotted path like: 'docutils.nodes.paragraph' :param nodes.Node node: target node :return: full module dotted path @@ -109,8 +108,7 @@ def get_full_module_name(node: Node) -> str: def repr_domxml(node: Node, length: int = 80) -> str: - """ - Return DOM XML representation of the specified node like: + """Return DOM XML representation of the specified node like: 'Added in version...' :param nodes.Node node: target node diff --git a/sphinx/writers/html5.py b/sphinx/writers/html5.py index 7b7f04290..d65823026 100644 --- a/sphinx/writers/html5.py +++ b/sphinx/writers/html5.py @@ -44,9 +44,7 @@ def multiply_length(length: str, scale: int) -> str: class HTML5Translator(SphinxTranslator, BaseTranslator): # type: ignore[misc] - """ - Our custom HTML translator. - """ + """Our custom HTML translator.""" builder: StandaloneHTMLBuilder # Override docutils.writers.html5_polyglot:HTMLTranslator diff --git a/sphinx/writers/manpage.py b/sphinx/writers/manpage.py index 7053a5f7c..8441c7e44 100644 --- a/sphinx/writers/manpage.py +++ b/sphinx/writers/manpage.py @@ -41,8 +41,7 @@ class ManualPageWriter(Writer): # type: ignore[misc] class NestedInlineTransform: - """ - Flatten nested inline nodes: + """Flatten nested inline nodes: Before: foo=1 @@ -73,9 +72,7 @@ class NestedInlineTransform: class ManualPageTranslator(SphinxTranslator, BaseTranslator): # type: ignore[misc] - """ - Custom man page translator. - """ + """Custom man page translator.""" _docinfo: dict[str, Any] = {} diff --git a/tests/roots/test-ext-autodoc/target/__init__.py b/tests/roots/test-ext-autodoc/target/__init__.py index 8b9c445c5..cab68e400 100644 --- a/tests/roots/test-ext-autodoc/target/__init__.py +++ b/tests/roots/test-ext-autodoc/target/__init__.py @@ -22,9 +22,7 @@ class CustomEx(Exception): def _funky_classmethod(name, b, c, d, docstring=None): - """ - Generates a classmethod for a class from a template by filling out some arguments. - """ + """Generates a classmethod for a class from a template by filling out some arguments.""" def template(cls, a, b, c, d=4, e=5, f=6): return a, b, c, d, e, f @@ -95,9 +93,7 @@ class CustomDict(dict): # NoQA: FURB189 def function(foo, *args, **kwds): - """ - Return spam. - """ + """Return spam.""" pass diff --git a/tests/roots/test-ext-autodoc/target/empty_all.py b/tests/roots/test-ext-autodoc/target/empty_all.py index b01855ace..94d0dd7e3 100644 --- a/tests/roots/test-ext-autodoc/target/empty_all.py +++ b/tests/roots/test-ext-autodoc/target/empty_all.py @@ -1,6 +1,4 @@ -""" -docsting of empty_all module. -""" +"""docsting of empty_all module.""" __all__ = [] diff --git a/tests/roots/test-ext-autodoc/target/inherited_annotations.py b/tests/roots/test-ext-autodoc/target/inherited_annotations.py index 896cc1fb8..abd16f5c8 100644 --- a/tests/roots/test-ext-autodoc/target/inherited_annotations.py +++ b/tests/roots/test-ext-autodoc/target/inherited_annotations.py @@ -1,5 +1,4 @@ -""" -Test case for #11387 corner case involving inherited +"""Test case for #11387 corner case involving inherited members with type annotations on python 3.9 and earlier """ diff --git a/tests/roots/test-ext-autodoc/target/process_docstring.py b/tests/roots/test-ext-autodoc/target/process_docstring.py index 6005943b6..492e51692 100644 --- a/tests/roots/test-ext-autodoc/target/process_docstring.py +++ b/tests/roots/test-ext-autodoc/target/process_docstring.py @@ -1,6 +1,5 @@ def func(): - """ - first line + """first line --- second line --- diff --git a/tests/roots/test-ext-autosummary-ext/dummy_module.py b/tests/roots/test-ext-autosummary-ext/dummy_module.py index ac261c628..a54b8362a 100644 --- a/tests/roots/test-ext-autosummary-ext/dummy_module.py +++ b/tests/roots/test-ext-autosummary-ext/dummy_module.py @@ -7,7 +7,7 @@ C.prop_attr1 C.prop_attr2 C.C2 -""" +""" # NoQA: D212 def with_sentence(): @@ -41,8 +41,7 @@ module_attr = 1 class C: - """ - My C class + """My C class with class_attr attribute """ @@ -59,8 +58,7 @@ class C: self.instance_attr = '42' def _prop_attr_get(self): - """ - This is a function docstring + """This is a function docstring return value is string. """ @@ -76,9 +74,7 @@ class C: """ class C2: - """ - This is a nested inner class docstring - """ + """This is a nested inner class docstring""" def func(arg_, *args, **kwargs): diff --git a/tests/roots/test-ext-autosummary-ext/underscore_module_.py b/tests/roots/test-ext-autosummary-ext/underscore_module_.py index 526affa5e..908015ac8 100644 --- a/tests/roots/test-ext-autosummary-ext/underscore_module_.py +++ b/tests/roots/test-ext-autosummary-ext/underscore_module_.py @@ -1,6 +1,4 @@ -""" -module with trailing underscores everywhere -""" +"""module with trailing underscores everywhere""" class class_: diff --git a/tests/roots/test-ext-doctest-with-autodoc/dir/bar.py b/tests/roots/test-ext-doctest-with-autodoc/dir/bar.py index 122fdf736..d13536e69 100644 --- a/tests/roots/test-ext-doctest-with-autodoc/dir/bar.py +++ b/tests/roots/test-ext-doctest-with-autodoc/dir/bar.py @@ -1,4 +1 @@ -""" ->>> 'dir/bar.py:2' - -""" +""">>> 'dir/bar.py:2'""" diff --git a/tests/roots/test-ext-doctest-with-autodoc/foo.py b/tests/roots/test-ext-doctest-with-autodoc/foo.py index 9f62a19b1..ac8ce857c 100644 --- a/tests/roots/test-ext-doctest-with-autodoc/foo.py +++ b/tests/roots/test-ext-doctest-with-autodoc/foo.py @@ -1,5 +1 @@ -""" - ->>> 'foo.py:3' - -""" +""">>> 'foo.py:3'""" diff --git a/tests/roots/test-ext-napoleon/mypackage/typehints.py b/tests/roots/test-ext-napoleon/mypackage/typehints.py index 526b78e40..6a2838b12 100644 --- a/tests/roots/test-ext-napoleon/mypackage/typehints.py +++ b/tests/roots/test-ext-napoleon/mypackage/typehints.py @@ -1,6 +1,5 @@ def hello(x: int, *args: int, **kwargs: int) -> None: - """ - Parameters + """Parameters ---------- x X diff --git a/tests/roots/test-ext-viewcode-find-package/main_package/subpackage/_subpackage2/submodule.py b/tests/roots/test-ext-viewcode-find-package/main_package/subpackage/_subpackage2/submodule.py index a8f8acc83..8aefb9457 100644 --- a/tests/roots/test-ext-viewcode-find-package/main_package/subpackage/_subpackage2/submodule.py +++ b/tests/roots/test-ext-viewcode-find-package/main_package/subpackage/_subpackage2/submodule.py @@ -1,6 +1,4 @@ -""" -submodule -""" +"""submodule""" # raise RuntimeError('This module should not get imported') @@ -10,23 +8,17 @@ def decorator(f): @decorator def func1(a, b): - """ - this is func1 - """ + """this is func1""" return a, b @decorator class Class1: - """ - this is Class1 - """ + """this is Class1""" class Class3: - """ - this is Class3 - """ + """this is Class3""" class_attr = 42 """this is the class attribute class_attr""" diff --git a/tests/roots/test-ext-viewcode-find/not_a_package/submodule.py b/tests/roots/test-ext-viewcode-find/not_a_package/submodule.py index 67bca1c2e..48171d76a 100644 --- a/tests/roots/test-ext-viewcode-find/not_a_package/submodule.py +++ b/tests/roots/test-ext-viewcode-find/not_a_package/submodule.py @@ -1,6 +1,6 @@ """ submodule -""" +""" # NoQA: D212 raise RuntimeError('This module should not get imported') # NoQA: EM101,TRY003 @@ -13,21 +13,17 @@ def decorator(f): def func1(a, b): """ this is func1 - """ + """ # NoQA: D212 return a, b @decorator class Class1: - """ - this is Class1 - """ + """this is Class1""" class Class3: - """ - this is Class3 - """ + """this is Class3""" class_attr = 42 """this is the class attribute class_attr""" diff --git a/tests/roots/test-ext-viewcode/spam/mod1.py b/tests/roots/test-ext-viewcode/spam/mod1.py index 13f432822..bf5c0fc38 100644 --- a/tests/roots/test-ext-viewcode/spam/mod1.py +++ b/tests/roots/test-ext-viewcode/spam/mod1.py @@ -1,6 +1,4 @@ -""" -mod1 -""" +"""mod1""" def decorator(f): @@ -9,23 +7,17 @@ def decorator(f): @decorator def func1(a, b): - """ - this is func1 - """ + """this is func1""" return a, b @decorator class Class1: - """ - this is Class1 - """ + """this is Class1""" class Class3: - """ - this is Class3 - """ + """this is Class3""" class_attr = 42 """this is the class attribute class_attr""" diff --git a/tests/roots/test-ext-viewcode/spam/mod2.py b/tests/roots/test-ext-viewcode/spam/mod2.py index 72cb08978..9a77a10e2 100644 --- a/tests/roots/test-ext-viewcode/spam/mod2.py +++ b/tests/roots/test-ext-viewcode/spam/mod2.py @@ -1,6 +1,4 @@ -""" -mod2 -""" +"""mod2""" def decorator(f): @@ -9,14 +7,10 @@ def decorator(f): @decorator def func2(a, b): - """ - this is func2 - """ + """this is func2""" return a, b @decorator class Class2: - """ - this is Class2 - """ + """this is Class2""" diff --git a/tests/roots/test-inheritance/dummy/test.py b/tests/roots/test-inheritance/dummy/test.py index 75c65cd54..e3838e7f0 100644 --- a/tests/roots/test-inheritance/dummy/test.py +++ b/tests/roots/test-inheritance/dummy/test.py @@ -1,6 +1,4 @@ -r""" - - Test with a class diagram like this:: +r"""Test with a class diagram like this:: A / \ diff --git a/tests/roots/test-root/autodoc_target.py b/tests/roots/test-root/autodoc_target.py index e320bddbb..df9e6b853 100644 --- a/tests/roots/test-root/autodoc_target.py +++ b/tests/roots/test-root/autodoc_target.py @@ -46,9 +46,7 @@ class CustomDataDescriptor2(CustomDataDescriptor): def _funky_classmethod(name, b, c, d, docstring=None): - """ - Generates a classmethod for a class from a template by filling out some arguments. - """ + """Generates a classmethod for a class from a template by filling out some arguments.""" def template(cls, a, b, c, d=4, e=5, f=6): return a, b, c, d, e, f @@ -136,9 +134,7 @@ class CustomDict(dict): # NoQA: FURB189 def function(foo, *args, **kwds): - """ - Return spam. - """ + """Return spam.""" pass @@ -216,9 +212,7 @@ class InstAttCls: class EnumCls(enum.Enum): - """ - this is enum class - """ + """this is enum class""" #: doc for val1 val1 = 12 diff --git a/tests/roots/test-warnings/autodoc_fodder.py b/tests/roots/test-warnings/autodoc_fodder.py index 59e4e210f..eb48b9be8 100644 --- a/tests/roots/test-warnings/autodoc_fodder.py +++ b/tests/roots/test-warnings/autodoc_fodder.py @@ -1,6 +1,5 @@ class MarkupError: - """ - .. note:: This is a docstring with a + """.. note:: This is a docstring with a small markup error which should have correct location information. """ diff --git a/tests/test_builders/test_build_html_copyright.py b/tests/test_builders/test_build_html_copyright.py index 69ddd2d1f..f91ebbdb8 100644 --- a/tests/test_builders/test_build_html_copyright.py +++ b/tests/test_builders/test_build_html_copyright.py @@ -11,8 +11,7 @@ LOCALTIME_2009 = type(LT)(LT_NEW) @pytest.fixture def no_source_date_year(monkeypatch): - """ - Explicitly clear SOURCE_DATE_EPOCH from the environment; this + """Explicitly clear SOURCE_DATE_EPOCH from the environment; this fixture can be used to ensure that copyright substitution logic does not occur during selected test cases. """ diff --git a/tests/test_builders/test_build_linkcheck.py b/tests/test_builders/test_build_linkcheck.py index d50200679..120575b57 100644 --- a/tests/test_builders/test_build_linkcheck.py +++ b/tests/test_builders/test_build_linkcheck.py @@ -488,8 +488,7 @@ def custom_handler( valid_credentials: tuple[str, str] | None = None, success_criteria: Callable[[Any], bool] = lambda _: True, ) -> type[BaseHTTPRequestHandler]: - """ - Returns an HTTP request handler that authenticates the client and then determines + """Returns an HTTP request handler that authenticates the client and then determines an appropriate HTTP response code, based on caller-provided credentials and optional success criteria, respectively. """ diff --git a/tests/test_extensions/ext_napoleon_pep526_data_numpy.py b/tests/test_extensions/ext_napoleon_pep526_data_numpy.py index 0681a334a..9738f84c7 100644 --- a/tests/test_extensions/ext_napoleon_pep526_data_numpy.py +++ b/tests/test_extensions/ext_napoleon_pep526_data_numpy.py @@ -7,8 +7,7 @@ module_level_var: int = 99 class PEP526NumpyClass: - """ - Sample class with PEP 526 annotations and numpy docstring + """Sample class with PEP 526 annotations and numpy docstring Attributes ---------- diff --git a/tests/test_extensions/test_ext_autodoc.py b/tests/test_extensions/test_ext_autodoc.py index 198e4c7c9..380008c29 100644 --- a/tests/test_extensions/test_ext_autodoc.py +++ b/tests/test_extensions/test_ext_autodoc.py @@ -243,8 +243,7 @@ def test_format_signature(app): """some docstring for F2.""" def __init__(self, *args, **kw): - """ - __init__(a1, a2, kw1=True, kw2=False) + """__init__(a1, a2, kw1=True, kw2=False) some docstring for __init__. """ @@ -363,9 +362,7 @@ def test_get_doc(app): """Docstring""" def g(): - """ - Docstring - """ + """Docstring""" for func in (f, g): assert getdocl('function', func) == ['Docstring'] diff --git a/tests/test_extensions/test_ext_napoleon.py b/tests/test_extensions/test_ext_napoleon.py index a603d894b..53f645302 100644 --- a/tests/test_extensions/test_ext_napoleon.py +++ b/tests/test_extensions/test_ext_napoleon.py @@ -13,9 +13,7 @@ from sphinx.ext.napoleon import Config, _process_docstring, _skip_member, setup def simple_decorator(f): - """ - A simple decorator that does nothing, for tests to use. - """ + """A simple decorator that does nothing, for tests to use.""" @functools.wraps(f) def wrapper(*args, **kwargs): diff --git a/tests/test_extensions/test_ext_todo.py b/tests/test_extensions/test_ext_todo.py index 626afe112..27a92100b 100644 --- a/tests/test_extensions/test_ext_todo.py +++ b/tests/test_extensions/test_ext_todo.py @@ -94,8 +94,7 @@ def test_todo_not_included(app): confoverrides={'todo_include_todos': True}, ) def test_todo_valid_link(app): - """ - Test that the inserted "original entry" links for todo items have a target + """Test that the inserted "original entry" links for todo items have a target that exists in the LaTeX output. The target was previously incorrectly omitted (GitHub issue #1020). """ diff --git a/tests/test_extensions/test_ext_viewcode.py b/tests/test_extensions/test_ext_viewcode.py index 92455ee5a..cb6b29859 100644 --- a/tests/test_extensions/test_ext_viewcode.py +++ b/tests/test_extensions/test_ext_viewcode.py @@ -48,9 +48,10 @@ def check_viewcode_output(app: SphinxTestApp) -> str: ) in result assert '@decorator\n' in result assert f'class{sp}Class1:\n' in result - assert ' """\n' in result - assert ' this is Class1\n' in result - assert ' """\n' in result + assert ( + ' ' + '"""this is Class1"""\n' + ) in result return result diff --git a/tests/test_markup/test_metadata.py b/tests/test_markup/test_metadata.py index c84dc4308..d10dcbc58 100644 --- a/tests/test_markup/test_metadata.py +++ b/tests/test_markup/test_metadata.py @@ -9,8 +9,7 @@ import pytest @pytest.mark.sphinx('dummy', testroot='metadata') def test_docinfo(app): - """ - Inspect the 'docinfo' metadata stored in the first node of the document. + """Inspect the 'docinfo' metadata stored in the first node of the document. Note this doesn't give us access to data stored in subsequence blocks that might be considered document metadata, such as 'abstract' or 'dedication' blocks, or the 'meta' role. Doing otherwise is probably more diff --git a/tests/test_search.py b/tests/test_search.py index 600f66cb9..87d4896b8 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -425,8 +425,7 @@ def test_search_index_is_deterministic(app): def is_title_tuple_type(item: list[int | str]) -> bool: - """ - In the search index, titles inside .alltitles are stored as a tuple of + """In the search index, titles inside .alltitles are stored as a tuple of (document_idx, title_anchor). Tuples are represented as lists in JSON, but their contents must not be sorted. We cannot sort them anyway, as document_idx is an int and title_anchor is a str. diff --git a/tests/test_util/test_util_inspect.py b/tests/test_util/test_util_inspect.py index 3db679b3d..c04086cca 100644 --- a/tests/test_util/test_util_inspect.py +++ b/tests/test_util/test_util_inspect.py @@ -943,9 +943,8 @@ def test_getdoc_inherited_classmethod(): class Foo: @classmethod def meth(cls): - """ - Docstring - indented text + """Docstring + indented text """ class Bar(Foo): @@ -961,9 +960,8 @@ def test_getdoc_inherited_classmethod(): def test_getdoc_inherited_decorated_method(): class Foo: def meth(self): - """ - Docstring - indented text + """Docstring + indented text """ class Bar(Foo): diff --git a/tests/test_util/test_util_nodes.py b/tests/test_util/test_util_nodes.py index 9595e4a64..ba8b1d68a 100644 --- a/tests/test_util/test_util_nodes.py +++ b/tests/test_util/test_util_nodes.py @@ -161,8 +161,7 @@ def test_extract_messages(rst, node_cls, count): def test_extract_messages_without_rawsource(): - """ - Check node.rawsource is fall-backed by using node.astext() value. + """Check node.rawsource is fall-backed by using node.astext() value. `extract_message` which is used from Sphinx i18n feature drop ``not node.rawsource`` nodes. So, all nodes which want to translate must have ``rawsource`` value. diff --git a/tests/utils.py b/tests/utils.py index 9ebe62ec2..8972740b8 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -28,8 +28,7 @@ CERT_FILE: Final[str] = str(TESTS_ROOT / 'certs' / 'cert.pem') class HttpServerThread(Thread): def __init__(self, handler: type[BaseRequestHandler], *, port: int = 0) -> None: - """ - Constructs a threaded HTTP server. The default port number of ``0`` + """Constructs a threaded HTTP server. The default port number of ``0`` delegates selection of a port number to bind to to Python. Ref: https://docs.python.org/3.11/library/socketserver.html#asynchronous-mixins @@ -77,8 +76,7 @@ def http_server( @contextmanager def rewrite_hyperlinks(app: Sphinx, server: HTTPServer) -> Iterator[None]: - """ - Rewrite hyperlinks that refer to network location 'localhost:7777', + """Rewrite hyperlinks that refer to network location 'localhost:7777', allowing that location to vary dynamically with the arbitrary test HTTP server port assigned during unit testing. @@ -109,8 +107,7 @@ def serve_application( tls_enabled: bool = False, port: int = 0, ) -> Iterator[str]: - """ - Prepare a temporary server to handle HTTP requests related to the links + """Prepare a temporary server to handle HTTP requests related to the links found in a Sphinx application project. :param app: The Sphinx application. diff --git a/utils/babel_runner.py b/utils/babel_runner.py index 3bb42efc3..45e97d2e6 100644 --- a/utils/babel_runner.py +++ b/utils/babel_runner.py @@ -163,8 +163,7 @@ def run_update() -> None: def run_compile() -> None: - """ - Catalog compilation command. + """Catalogue compilation command. An extended command that writes all message strings that occur in JavaScript files to a JavaScript file along with the .mo file.