diff options
author | Daniel Eades <danieleades@hotmail.com> | 2022-12-15 17:22:07 +0000 |
---|---|---|
committer | Jean-François B <2589111+jfbu@users.noreply.github.com> | 2022-12-16 16:50:24 +0100 |
commit | 1abb24e309c8189eca2663f77c3a3aa866633e12 (patch) | |
tree | e74425a4c2647b8a5c6c7c980f00235fc12491b5 | |
parent | dc29bf9abef764460ec5ec1c1571bddce9a4f7fa (diff) | |
download | sphinx-git-1abb24e309c8189eca2663f77c3a3aa866633e12.tar.gz |
remove blanket 'noqas'
38 files changed, 156 insertions, 93 deletions
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 86e02fd28..000000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,9 +0,0 @@ -repos: - - repo: https://github.com/asottile/yesqa - rev: v1.4.0 - hooks: - - id: yesqa - additional_dependencies: - - flake8-comprehensions - - flake8-bugbear - - flake8-simplify diff --git a/doc/conf.py b/doc/conf.py index 157836f10..b17287d54 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -124,7 +124,7 @@ gettext_compact = False # -- Extension interface ------------------------------------------------------- -from sphinx import addnodes # noqa +from sphinx import addnodes # noqa: E402 event_sig_re = re.compile(r'([a-zA-Z-]+)\s*\((.*)\)') @@ -185,8 +185,10 @@ def setup(app): # Load jQuery and patches to make readthedocs-doc-embed.js available (refs: #10574) app.add_js_file('https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js', priority=100) - app.add_js_file('https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.1/underscore-min.js', # NoQA - priority=100) + app.add_js_file( + 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.1/underscore-min.js', + priority=100, + ) app.add_js_file('_sphinx_javascript_frameworks_compat.js', priority=105) # workaround for RTD diff --git a/sphinx/application.py b/sphinx/application.py index 05a05931c..1aa71d828 100644 --- a/sphinx/application.py +++ b/sphinx/application.py @@ -43,7 +43,7 @@ from sphinx.util.tags import Tags from sphinx.util.typing import RoleFunction, TitleGetter if TYPE_CHECKING: - from docutils.nodes import Node # NOQA + from docutils.nodes import Node # noqa: F401 from sphinx.builders import Builder @@ -934,7 +934,7 @@ class Sphinx: refs: `Transform Priority Range Categories`__ __ https://docutils.sourceforge.io/docs/ref/transforms.html#transform-priority-range-categories - """ # NOQA + """ # noqa: E501 self.registry.add_transform(transform) def add_post_transform(self, transform: Type[Transform]) -> None: diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py index e70d1956c..1ca5eb317 100644 --- a/sphinx/builders/__init__.py +++ b/sphinx/builders/__init__.py @@ -31,8 +31,8 @@ from sphinx.util.tags import Tags from sphinx.util.typing import NoneType # side effect: registers roles and directives -from sphinx import directives # NOQA isort:skip -from sphinx import roles # NOQA isort:skip +from sphinx import directives # noqa: F401 isort:skip +from sphinx import roles # noqa: F401 isort:skip try: import multiprocessing except ImportError: @@ -541,7 +541,12 @@ class Builder: with open(doctree_filename, 'wb') as f: pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL) - def write(self, build_docnames: Iterable[str], updated_docnames: Sequence[str], method: str = 'update') -> None: # NOQA + def write( + self, + build_docnames: Iterable[str], + updated_docnames: Sequence[str], + method: str = 'update' + ) -> None: if build_docnames is None or build_docnames == ['__all__']: # build_all build_docnames = self.env.found_docs diff --git a/sphinx/builders/_epub_base.py b/sphinx/builders/_epub_base.py index 422fd448f..2fc093522 100644 --- a/sphinx/builders/_epub_base.py +++ b/sphinx/builders/_epub_base.py @@ -179,7 +179,9 @@ class EpubBuilder(StandaloneHTMLBuilder): self.id_cache[name] = id return id - def get_refnodes(self, doctree: Node, result: List[Dict[str, Any]]) -> List[Dict[str, Any]]: # NOQA + def get_refnodes( + self, doctree: Node, result: List[Dict[str, Any]] + ) -> List[Dict[str, Any]]: """Collect section titles, their depth in the toc and the refuri.""" # XXX: is there a better way than checking the attribute # toctree-l[1-8] on the parent node? diff --git a/sphinx/builders/html/__init__.py b/sphinx/builders/html/__init__.py index d5264e43e..4593852d3 100644 --- a/sphinx/builders/html/__init__.py +++ b/sphinx/builders/html/__init__.py @@ -156,7 +156,9 @@ class BuildInfo: except Exception as exc: raise ValueError(__('build info file is broken: %r') % exc) from exc - def __init__(self, config: Config = None, tags: Tags = None, config_categories: List[str] = []) -> None: # NOQA + def __init__( + self, config: Config = None, tags: Tags = None, config_categories: List[str] = [] + ) -> None: self.config_hash = '' self.tags_hash = '' @@ -1035,7 +1037,9 @@ class StandaloneHTMLBuilder(Builder): else: ctx['pageurl'] = None - def pathto(otheruri: str, resource: bool = False, baseuri: str = default_baseuri) -> str: # NOQA + def pathto( + otheruri: str, resource: bool = False, baseuri: str = default_baseuri + ) -> str: if resource and '://' in otheruri: # allow non-local resources given by scheme return otheruri @@ -1314,10 +1318,10 @@ def deprecate_html_4(_app: Sphinx, config: Config) -> None: # for compatibility -import sphinxcontrib.serializinghtml # NOQA +import sphinxcontrib.serializinghtml # noqa: E402,F401 -import sphinx.builders.dirhtml # NOQA -import sphinx.builders.singlehtml # NOQA +import sphinx.builders.dirhtml # noqa: E402,F401 +import sphinx.builders.singlehtml # noqa: E402,F401 deprecated_alias('sphinx.builders.html', { @@ -1371,7 +1375,7 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.add_config_value('html_search_scorer', '', None) app.add_config_value('html_scaled_image_link', True, 'html') app.add_config_value('html_baseurl', '', 'html') - app.add_config_value('html_codeblock_linenos_style', 'inline', 'html', # RemovedInSphinx70Warning # NOQA + app.add_config_value('html_codeblock_linenos_style', 'inline', 'html', # RemovedInSphinx70Warning # noqa: E501 ENUM('table', 'inline')) app.add_config_value('html_math_renderer', None, 'env') app.add_config_value('html4_writer', False, 'html') diff --git a/sphinx/builders/latex/__init__.py b/sphinx/builders/latex/__init__.py index 3344095f8..b80ce01e5 100644 --- a/sphinx/builders/latex/__init__.py +++ b/sphinx/builders/latex/__init__.py @@ -8,7 +8,7 @@ from typing import Any, Dict, Iterable, List, Optional, Tuple, Union from docutils.frontend import OptionParser from docutils.nodes import Node -import sphinx.builders.latex.nodes # NOQA # Workaround: import this before writer to avoid ImportError +import sphinx.builders.latex.nodes # noqa: F401,E501 # Workaround: import this before writer to avoid ImportError from sphinx import addnodes, highlighting, package_dir from sphinx.application import Sphinx from sphinx.builders import Builder @@ -321,7 +321,9 @@ class LaTeXBuilder(Builder): self.context['pointsize'] = theme.pointsize self.context['wrapperclass'] = theme.wrapperclass - def assemble_doctree(self, indexfile: str, toctree_only: bool, appendices: List[str]) -> nodes.document: # NOQA + def assemble_doctree( + self, indexfile: str, toctree_only: bool, appendices: List[str] + ) -> nodes.document: self.docnames = set([indexfile] + appendices) logger.info(darkgreen(indexfile) + " ", nonl=True) tree = self.env.get_doctree(indexfile) diff --git a/sphinx/builders/latex/transforms.py b/sphinx/builders/latex/transforms.py index de3f3ff03..d994fa141 100644 --- a/sphinx/builders/latex/transforms.py +++ b/sphinx/builders/latex/transforms.py @@ -106,7 +106,9 @@ class ShowUrlsTransform(SphinxPostTransform): raise ValueError('Failed to get a docname!') from None raise ValueError(f'Failed to get a docname for source {source!r}!') - def create_footnote(self, uri: str, docname: str) -> Tuple[nodes.footnote, nodes.footnote_reference]: # NOQA + def create_footnote( + self, uri: str, docname: str + ) -> Tuple[nodes.footnote, nodes.footnote_reference]: reference = nodes.reference('', nodes.Text(uri), refuri=uri, nolinkurl=True) footnote = nodes.footnote(uri, auto=1, docname=docname) footnote['names'].append('#') diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py index ee869dc7d..71fcbed57 100644 --- a/sphinx/builders/texinfo.py +++ b/sphinx/builders/texinfo.py @@ -122,7 +122,9 @@ class TexinfoBuilder(Builder): docwriter.write(doctree, destination) self.copy_image_files(targetname[:-5]) - def assemble_doctree(self, indexfile: str, toctree_only: bool, appendices: List[str]) -> nodes.document: # NOQA + def assemble_doctree( + self, indexfile: str, toctree_only: bool, appendices: List[str] + ) -> nodes.document: self.docnames = set([indexfile] + appendices) logger.info(darkgreen(indexfile) + " ", nonl=True) tree = self.env.get_doctree(indexfile) @@ -192,7 +194,9 @@ class TexinfoBuilder(Builder): logger.warning(__("error writing file Makefile: %s"), err) -def default_texinfo_documents(config: Config) -> List[Tuple[str, str, str, str, str, str, str]]: # NOQA +def default_texinfo_documents( + config: Config +) -> List[Tuple[str, str, str, str, str, str, str]]: """ Better default texinfo_documents settings. """ filename = make_filename_from_project(config.project) return [(config.root_doc, filename, config.project, config.author, filename, diff --git a/sphinx/cmd/quickstart.py b/sphinx/cmd/quickstart.py index 670a8ee02..5139fe227 100644 --- a/sphinx/cmd/quickstart.py +++ b/sphinx/cmd/quickstart.py @@ -239,9 +239,9 @@ def ask_user(d: Dict[str, Any]) -> None: if 'dot' not in d: print() - print(__('Inside the root directory, two more directories will be created; "_templates"\n' # NOQA - 'for custom HTML templates and "_static" for custom stylesheets and other static\n' # NOQA - 'files. You can enter another prefix (such as ".") to replace the underscore.')) # NOQA + print(__('Inside the root directory, two more directories will be created; "_templates"\n' # noqa: E501 + 'for custom HTML templates and "_static" for custom stylesheets and other static\n' # noqa: E501 + 'files. You can enter another prefix (such as ".") to replace the underscore.')) # noqa: E501 d['dot'] = do_prompt(__('Name prefix for templates and static dir'), '_', ok) if 'project' not in d: @@ -264,12 +264,14 @@ def ask_user(d: Dict[str, Any]) -> None: if 'language' not in d: print() - print(__('If the documents are to be written in a language other than English,\n' - 'you can select a language here by its language code. Sphinx will then\n' - 'translate text that it generates into that language.\n' - '\n' - 'For a list of supported codes, see\n' - 'https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.')) # NOQA + print(__( + 'If the documents are to be written in a language other than English,\n' + 'you can select a language here by its language code. Sphinx will then\n' + 'translate text that it generates into that language.\n' + '\n' + 'For a list of supported codes, see\n' + 'https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.' + )) d['language'] = do_prompt(__('Project language'), 'en') if d['language'] == 'en': d['language'] = None diff --git a/sphinx/config.py b/sphinx/config.py index 2e5b00985..67e8a6f2a 100644 --- a/sphinx/config.py +++ b/sphinx/config.py @@ -380,7 +380,7 @@ def convert_source_suffix(app: "Sphinx", config: Config) -> None: config.source_suffix = OrderedDict({source_suffix: None}) # type: ignore elif isinstance(source_suffix, (list, tuple)): # if list, considers as all of them are default filetype - config.source_suffix = OrderedDict([(s, None) for s in source_suffix]) # type: ignore # NOQA + config.source_suffix = OrderedDict([(s, None) for s in source_suffix]) # type: ignore elif isinstance(source_suffix, dict): # if dict, convert it to OrderedDict config.source_suffix = OrderedDict(config.source_suffix) # type: ignore diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py index d33462dc0..a872b9e47 100644 --- a/sphinx/directives/code.py +++ b/sphinx/directives/code.py @@ -67,7 +67,9 @@ def dedent_lines( return new_lines -def container_wrapper(directive: SphinxDirective, literal_node: Node, caption: str) -> nodes.container: # NOQA +def container_wrapper( + directive: SphinxDirective, literal_node: Node, caption: str +) -> nodes.container: container_node = nodes.container('', literal_block=True, classes=['literal-block-wrapper']) parsed = nodes.Element() diff --git a/sphinx/directives/other.py b/sphinx/directives/other.py index 5292215a3..1826baee6 100644 --- a/sphinx/directives/other.py +++ b/sphinx/directives/other.py @@ -9,7 +9,7 @@ from docutils.parsers.rst.directives.misc import Class from docutils.parsers.rst.directives.misc import Include as BaseInclude from sphinx import addnodes -from sphinx.domains.changeset import VersionChange # NOQA # for compatibility +from sphinx.domains.changeset import VersionChange # noqa: F401 # for compatibility from sphinx.locale import _, __ from sphinx.util import docname_join, logging, url_re from sphinx.util.docutils import SphinxDirective diff --git a/sphinx/domains/c.py b/sphinx/domains/c.py index 7475f0442..559aa8b25 100644 --- a/sphinx/domains/c.py +++ b/sphinx/domains/c.py @@ -1743,7 +1743,7 @@ class Symbol: Symbol.debug_indent -= 2 def _symbol_lookup(self, nestedName: ASTNestedName, - onMissingQualifiedSymbol: Callable[["Symbol", ASTIdentifier], "Symbol"], # NOQA + onMissingQualifiedSymbol: Callable[["Symbol", ASTIdentifier], "Symbol"], ancestorLookupType: str, matchSelf: bool, recurseInAnon: bool, searchInSiblings: bool) -> SymbolLookupResult: # TODO: further simplification from C++ to C @@ -1948,7 +1948,9 @@ class Symbol: # if there is an empty symbol, fill that one if len(noDecl) == 0: if Symbol.debug_lookup: - Symbol.debug_print("no match, no empty, candSybmol is not None?:", candSymbol is not None) # NOQA + Symbol.debug_print( + "no match, no empty, candSybmol is not None?:", candSymbol is not None, + ) Symbol.debug_indent -= 2 if candSymbol is not None: return candSymbol @@ -3684,7 +3686,7 @@ class CDomain(Domain): 'enumerator': ObjType(_('enumerator'), 'enumerator', 'identifier'), 'type': ObjType(_('type'), 'identifier', 'type'), # generated object types - 'functionParam': ObjType(_('function parameter'), 'identifier', 'var', 'member', 'data'), # noqa + 'functionParam': ObjType(_('function parameter'), 'identifier', 'var', 'member', 'data'), # noqa: E501 } directives = { diff --git a/sphinx/domains/changeset.py b/sphinx/domains/changeset.py index 40e46159c..4a5a97f2c 100644 --- a/sphinx/domains/changeset.py +++ b/sphinx/domains/changeset.py @@ -135,7 +135,9 @@ class ChangeSetDomain(Domain): if changeset.docname in docnames: changes.append(changeset) - def process_doc(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA + def process_doc( + self, env: "BuildEnvironment", docname: str, document: nodes.document + ) -> None: pass # nothing to do here. All changesets are registered on calling directive. def get_changesets_for(self, version: str) -> List[ChangeSet]: diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py index 7523a1e9f..b29e4bf39 100644 --- a/sphinx/domains/cpp.py +++ b/sphinx/domains/cpp.py @@ -4494,12 +4494,18 @@ class Symbol: if Symbol.debug_lookup: Symbol.debug_indent -= 2 - def _symbol_lookup(self, nestedName: ASTNestedName, templateDecls: List[Any], - onMissingQualifiedSymbol: Callable[["Symbol", Union[ASTIdentifier, ASTOperator], Any, ASTTemplateArgs], "Symbol"], # NOQA - strictTemplateParamArgLists: bool, ancestorLookupType: str, - templateShorthand: bool, matchSelf: bool, - recurseInAnon: bool, correctPrimaryTemplateArgs: bool, - searchInSiblings: bool) -> SymbolLookupResult: + def _symbol_lookup( + self, + nestedName: ASTNestedName, + templateDecls: List[Any], + onMissingQualifiedSymbol: Callable[ + ["Symbol", Union[ASTIdentifier, ASTOperator], Any, ASTTemplateArgs], "Symbol" + ], + strictTemplateParamArgLists: bool, ancestorLookupType: str, + templateShorthand: bool, matchSelf: bool, + recurseInAnon: bool, correctPrimaryTemplateArgs: bool, + searchInSiblings: bool + ) -> SymbolLookupResult: # ancestorLookupType: if not None, specifies the target type of the lookup if Symbol.debug_lookup: Symbol.debug_indent += 1 @@ -4788,7 +4794,10 @@ class Symbol: return makeCandSymbol() else: if Symbol.debug_lookup: - Symbol.debug_print("no match, but fill an empty declaration, candSybmol is not None?:", candSymbol is not None) # NOQA + Symbol.debug_print( + "no match, but fill an empty declaration, candSybmol is not None?:", + candSymbol is not None, + ) Symbol.debug_indent -= 2 if candSymbol is not None: candSymbol.remove() @@ -7839,9 +7848,9 @@ class CPPDomain(Domain): 'enum': ObjType(_('enum'), 'enum', 'identifier', 'type'), 'enumerator': ObjType(_('enumerator'), 'enumerator', 'identifier'), # generated object types - 'functionParam': ObjType(_('function parameter'), 'identifier', 'member', 'var'), # noqa + 'functionParam': ObjType(_('function parameter'), 'identifier', 'member', 'var'), # noqa: E501 'templateParam': ObjType(_('template parameter'), - 'identifier', 'class', 'struct', 'union', 'member', 'var', 'type'), # noqa + 'identifier', 'class', 'struct', 'union', 'member', 'var', 'type'), # noqa: E501 } directives = { diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py index 586ac4d20..898c6f94d 100644 --- a/sphinx/domains/std.py +++ b/sphinx/domains/std.py @@ -41,7 +41,7 @@ class GenericObject(ObjectDescription[str]): A generic x-ref directive registered with Sphinx.add_object_type(). """ indextemplate: str = '' - parse_node: Callable[["BuildEnvironment", str, desc_signature], str] = None # NOQA + parse_node: Callable[["BuildEnvironment", str, desc_signature], str] = None def handle_signature(self, sig: str, signode: desc_signature) -> str: if self.parse_node: @@ -729,7 +729,9 @@ class StandardDomain(Domain): if data[0] in docnames: self.anonlabels[key] = data - def process_doc(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA + def process_doc( + self, env: "BuildEnvironment", docname: str, document: nodes.document + ) -> None: for name, explicit in document.nametypes.items(): if not explicit: continue diff --git a/sphinx/environment/collectors/metadata.py b/sphinx/environment/collectors/metadata.py index c70a5d408..fc857d0a5 100644 --- a/sphinx/environment/collectors/metadata.py +++ b/sphinx/environment/collectors/metadata.py @@ -42,7 +42,7 @@ class MetadataCollector(EnvironmentCollector): md[field_name.astext()] = field_body.astext() elif isinstance(node, nodes.TextElement): # other children must be TextElement - # see: https://docutils.sourceforge.io/docs/ref/doctree.html#bibliographic-elements # NOQA + # see: https://docutils.sourceforge.io/docs/ref/doctree.html#bibliographic-elements # noqa: E501 md[node.__class__.__name__] = node.astext() for name, value in md.items(): diff --git a/sphinx/ext/mathjax.py b/sphinx/ext/mathjax.py index a9e4deba3..e87e9ea64 100644 --- a/sphinx/ext/mathjax.py +++ b/sphinx/ext/mathjax.py @@ -67,7 +67,10 @@ def html_visit_displaymath(self: HTMLTranslator, node: nodes.math_block) -> None def install_mathjax(app: Sphinx, pagename: str, templatename: str, context: Dict[str, Any], event_arg: Any) -> None: - if app.builder.format != 'html' or app.builder.math_renderer_name != 'mathjax': # type: ignore # NOQA + if ( + app.builder.format != 'html' or + app.builder.math_renderer_name != 'mathjax' # type: ignore[attr-defined] + ): return if not app.config.mathjax_path: raise ExtensionError('mathjax_path config value must be set for the ' diff --git a/sphinx/locale/__init__.py b/sphinx/locale/__init__.py index 61e3ae812..d0a83dc3d 100644 --- a/sphinx/locale/__init__.py +++ b/sphinx/locale/__init__.py @@ -224,7 +224,7 @@ def get_translation(catalog: str, namespace: str = 'general') -> Callable[[str], def gettext(message: str, *args: Any) -> str: if not is_translator_registered(catalog, namespace): # not initialized yet - return _TranslationProxy(_lazy_translate, catalog, namespace, message) # type: ignore[return-value] # NOQA + return _TranslationProxy(_lazy_translate, catalog, namespace, message) # type: ignore[return-value] # noqa: E501 else: translator = get_translator(catalog, namespace) if len(args) <= 1: diff --git a/sphinx/pycode/parser.py b/sphinx/pycode/parser.py index 7861e6b0f..d64fb9282 100644 --- a/sphinx/pycode/parser.py +++ b/sphinx/pycode/parser.py @@ -59,7 +59,10 @@ def get_lvar_names(node: ast.AST, self: Optional[ast.arg] = None) -> List[str]: pass return members elif node_name == 'Attribute': - if node.value.__class__.__name__ == 'Name' and self and node.value.id == self_id: # type: ignore # NOQA + if ( + node.value.__class__.__name__ == 'Name' and # type: ignore[attr-defined] + self and node.value.id == self_id # type: ignore[attr-defined] + ): # instance variable return ["%s" % get_lvar_names(node.attr, self)[0]] # type: ignore else: @@ -344,7 +347,9 @@ class VariableCommentPicker(ast.NodeVisitor): """Handles Assign node and pick up a variable comment.""" try: targets = get_assign_targets(node) - varnames: List[str] = sum([get_lvar_names(t, self=self.get_self()) for t in targets], []) # NOQA + varnames: List[str] = sum( + [get_lvar_names(t, self=self.get_self()) for t in targets], [] + ) current_line = self.get_line(node.lineno) except TypeError: return # this assignment is not new definition! diff --git a/sphinx/transforms/i18n.py b/sphinx/transforms/i18n.py index 188655845..552aa955f 100644 --- a/sphinx/transforms/i18n.py +++ b/sphinx/transforms/i18n.py @@ -311,8 +311,12 @@ class Locale(SphinxTransform): lst.append(new) is_autofootnote_ref = NodeMatcher(nodes.footnote_reference, auto=Any) - old_foot_refs: List[nodes.footnote_reference] = list(node.findall(is_autofootnote_ref)) # NOQA - new_foot_refs: List[nodes.footnote_reference] = list(patch.findall(is_autofootnote_ref)) # NOQA + old_foot_refs: List[nodes.footnote_reference] = list( + node.findall(is_autofootnote_ref) + ) + new_foot_refs: List[nodes.footnote_reference] = list( + patch.findall(is_autofootnote_ref) + ) if not noqa and len(old_foot_refs) != len(new_foot_refs): old_foot_ref_rawsources = [ref.rawsource for ref in old_foot_refs] new_foot_ref_rawsources = [ref.rawsource for ref in new_foot_refs] @@ -401,7 +405,9 @@ class Locale(SphinxTransform): # citation should use original 'ids'. is_citation_ref = NodeMatcher(nodes.citation_reference, refname=Any) old_cite_refs: List[nodes.citation_reference] = list(node.findall(is_citation_ref)) - new_cite_refs: List[nodes.citation_reference] = list(patch.findall(is_citation_ref)) # NOQA + new_cite_refs: List[nodes.citation_reference] = list( + patch.findall(is_citation_ref) + ) refname_ids_map = {} if not noqa and len(old_cite_refs) != len(new_cite_refs): old_cite_ref_rawsources = [ref.rawsource for ref in old_cite_refs] @@ -487,7 +493,7 @@ class Locale(SphinxTransform): node['entries'] = new_entries # remove translated attribute that is used for avoiding double translation. - for translated in self.document.findall(NodeMatcher(translated=Any)): # type: Element # NOQA + for translated in self.document.findall(NodeMatcher(translated=Any)): # type: Element translated.delattr('translated') diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py index 007a2bf5d..7d161b05f 100644 --- a/sphinx/util/__init__.py +++ b/sphinx/util/__init__.py @@ -22,13 +22,13 @@ from sphinx.errors import ExtensionError, FiletypeNotFoundError, SphinxParallelE from sphinx.locale import __ from sphinx.util import logging from sphinx.util.console import bold, colorize, strip_colors, term_width_line # type: ignore -from sphinx.util.matching import patfilter # noqa -from sphinx.util.nodes import (caption_ref_re, explicit_title_re, # noqa +from sphinx.util.matching import patfilter # noqa: F401 +from sphinx.util.nodes import (caption_ref_re, explicit_title_re, # noqa: F401 nested_parse_with_titles, split_explicit_title) # import other utilities; partly for backwards compatibility, so don't # prune unused ones indiscriminately -from sphinx.util.osutil import (SEP, copyfile, copytimes, ensuredir, make_filename, # noqa - mtimes_of_files, os_path, relative_uri) +from sphinx.util.osutil import (SEP, copyfile, copytimes, ensuredir, # noqa: F401,E501 + make_filename, mtimes_of_files, os_path, relative_uri) from sphinx.util.typing import PathMatcher if TYPE_CHECKING: @@ -61,7 +61,7 @@ def path_stabilize(filepath: str) -> str: def get_matching_files(dirname: str, exclude_matchers: Tuple[PathMatcher, ...] = (), - include_matchers: Tuple[PathMatcher, ...] = ()) -> Iterable[str]: # NOQA + include_matchers: Tuple[PathMatcher, ...] = ()) -> Iterable[str]: """Get all file names in a directory, recursively. Exclude files and dirs matching some matcher in *exclude_matchers*. @@ -507,7 +507,9 @@ class progress_message: def __enter__(self) -> None: logger.info(bold(self.message + '... '), nonl=True) - def __exit__(self, exc_type: Type[Exception], exc_value: Exception, traceback: Any) -> bool: # NOQA + def __exit__( + self, exc_type: Type[Exception], exc_value: Exception, traceback: Any + ) -> bool: if isinstance(exc_value, SkipProgressMessage): logger.info(__('skipped')) if exc_value.args: diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py index d27ad6ba0..e45cf0db9 100644 --- a/sphinx/util/docutils.py +++ b/sphinx/util/docutils.py @@ -242,7 +242,9 @@ class CustomReSTDispatcher: def __enter__(self) -> None: self.enable() - def __exit__(self, exc_type: Type[Exception], exc_value: Exception, traceback: Any) -> None: # NOQA + def __exit__( + self, exc_type: Type[Exception], exc_value: Exception, traceback: Any + ) -> None: self.disable() def enable(self) -> None: @@ -373,7 +375,7 @@ def switch_source_input(state: State, content: StringList) -> Generator[None, No # replace it by new one state_machine = StateMachine([], None) state_machine.input_lines = content - state.memo.reporter.get_source_and_line = state_machine.get_source_and_line # type: ignore # NOQA + state.memo.reporter.get_source_and_line = state_machine.get_source_and_line # type: ignore # noqa: E501 yield finally: diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py index 58ec9fae2..accbb2388 100644 --- a/sphinx/util/inspect.py +++ b/sphinx/util/inspect.py @@ -11,7 +11,7 @@ import types import typing from functools import cached_property, partial, partialmethod, singledispatchmethod from importlib import import_module -from inspect import (Parameter, isasyncgenfunction, isclass, ismethod, # NOQA +from inspect import (Parameter, isasyncgenfunction, isclass, ismethod, # noqa: F401 ismethoddescriptor, ismodule) from io import StringIO from types import (ClassMethodDescriptorType, MethodDescriptorType, MethodType, ModuleType, @@ -736,7 +736,9 @@ def signature_from_ast(node: ast.FunctionDef, code: str = '') -> inspect.Signatu if defaults[i + posonlyargs] is Parameter.empty: default = Parameter.empty else: - default = DefaultValue(ast_unparse(defaults[i + posonlyargs], code)) # type: ignore # NOQA + default = DefaultValue( + ast_unparse(defaults[i + posonlyargs], code) # type: ignore + ) annotation = ast_unparse(arg.annotation, code) or Parameter.empty params.append(Parameter(arg.arg, Parameter.POSITIONAL_OR_KEYWORD, @@ -751,7 +753,7 @@ def signature_from_ast(node: ast.FunctionDef, code: str = '') -> inspect.Signatu if args.kw_defaults[i] is None: default = Parameter.empty else: - default = DefaultValue(ast_unparse(args.kw_defaults[i], code)) # type: ignore # NOQA + default = DefaultValue(ast_unparse(args.kw_defaults[i], code)) # type: ignore annotation = ast_unparse(arg.annotation, code) or Parameter.empty params.append(Parameter(arg.arg, Parameter.KEYWORD_ONLY, default=default, annotation=annotation)) diff --git a/sphinx/util/logging.py b/sphinx/util/logging.py index 9b38aabdd..6f8b7096d 100644 --- a/sphinx/util/logging.py +++ b/sphinx/util/logging.py @@ -118,7 +118,9 @@ class SphinxLoggerAdapter(logging.LoggerAdapter): """LoggerAdapter allowing ``type`` and ``subtype`` keywords.""" KEYWORDS = ['type', 'subtype', 'location', 'nonl', 'color', 'once'] - def log(self, level: Union[int, str], msg: str, *args: Any, **kwargs: Any) -> None: # type: ignore # NOQA + def log( # type: ignore[override] + self, level: Union[int, str], msg: str, *args: Any, **kwargs: Any + ) -> None: if isinstance(level, int): super().log(level, msg, *args, **kwargs) else: diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py index 289dcc92e..cf8287f0b 100644 --- a/sphinx/util/nodes.py +++ b/sphinx/util/nodes.py @@ -291,7 +291,9 @@ def get_prev_node(node: Node) -> Optional[Node]: return None -def traverse_translatable_index(doctree: Element) -> Iterable[Tuple[Element, List["IndexEntry"]]]: # NOQA +def traverse_translatable_index( + doctree: Element +) -> Iterable[Tuple[Element, List["IndexEntry"]]]: """Traverse translatable index node from a document tree.""" matcher = NodeMatcher(addnodes.index, inline=False) for node in doctree.findall(matcher): # type: addnodes.index diff --git a/sphinx/util/osutil.py b/sphinx/util/osutil.py index bfc80adcf..e8d47c5c7 100644 --- a/sphinx/util/osutil.py +++ b/sphinx/util/osutil.py @@ -197,7 +197,9 @@ class FileAvoidWrite: def __enter__(self) -> "FileAvoidWrite": return self - def __exit__(self, exc_type: Type[Exception], exc_value: Exception, traceback: Any) -> bool: # NOQA + def __exit__( + self, exc_type: Type[Exception], exc_value: Exception, traceback: Any + ) -> bool: self.close() return True diff --git a/sphinx/writers/html.py b/sphinx/writers/html.py index 36b066158..938b6e77b 100644 --- a/sphinx/writers/html.py +++ b/sphinx/writers/html.py @@ -627,8 +627,10 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator): if not ('width' in node and 'height' in node): size = get_image_size(os.path.join(self.builder.srcdir, olduri)) if size is None: - logger.warning(__('Could not obtain image size. :scale: option is ignored.'), # NOQA - location=node) + logger.warning( + __('Could not obtain image size. :scale: option is ignored.'), + location=node, + ) else: if 'width' not in node: node['width'] = str(size[0]) diff --git a/sphinx/writers/html5.py b/sphinx/writers/html5.py index f8b22de27..6fe9b62fd 100644 --- a/sphinx/writers/html5.py +++ b/sphinx/writers/html5.py @@ -574,8 +574,10 @@ class HTML5Translator(SphinxTranslator, BaseTranslator): if not ('width' in node and 'height' in node): size = get_image_size(os.path.join(self.builder.srcdir, olduri)) if size is None: - logger.warning(__('Could not obtain image size. :scale: option is ignored.'), # NOQA - location=node) + logger.warning( + __('Could not obtain image size. :scale: option is ignored.'), + location=node, + ) else: if 'width' not in node: node['width'] = str(size[0]) diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py index e3011adf8..7bdde2166 100644 --- a/sphinx/writers/latex.py +++ b/sphinx/writers/latex.py @@ -2108,6 +2108,6 @@ class LaTeXTranslator(SphinxTranslator): # FIXME: Workaround to avoid circular import # refs: https://github.com/sphinx-doc/sphinx/issues/5433 -from sphinx.builders.latex.nodes import ( # NOQA isort:skip +from sphinx.builders.latex.nodes import ( # noqa: E402 # isort:skip HYPERLINK_SUPPORT_NODES, captioned_literal_block, footnotetext, ) diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py index aeb8e8f63..cbac28a2f 100644 --- a/sphinx/writers/texinfo.py +++ b/sphinx/writers/texinfo.py @@ -490,7 +490,9 @@ class TexinfoTranslator(SphinxTranslator): # this is copied from the latex writer # TODO: move this to sphinx.util - def collect_footnotes(self, node: Element) -> Dict[str, List[Union[collected_footnote, bool]]]: # NOQA + def collect_footnotes( + self, node: Element + ) -> Dict[str, List[Union[collected_footnote, bool]]]: def footnotes_under(n: Element) -> Iterator[nodes.footnote]: if isinstance(n, nodes.footnote): yield n diff --git a/tests/test_domain_c.py b/tests/test_domain_c.py index 9718297ab..ac9142e68 100644 --- a/tests/test_domain_c.py +++ b/tests/test_domain_c.py @@ -735,7 +735,7 @@ def test_domain_c_build_intersphinx(tempdir, app, status, warning): .. c:type:: _type .. c:function:: void _functionParam(int param) -""" # noqa +""" # noqa: F841 inv_file = tempdir / 'inventory' inv_file.write_bytes(b'''\ # Sphinx inventory version 2 @@ -755,7 +755,7 @@ _struct c:struct 1 index.html#c.$ - _type c:type 1 index.html#c.$ - _union c:union 1 index.html#c.$ - _var c:member 1 index.html#c.$ - -''')) # noqa +''')) # noqa: W291 app.config.intersphinx_mapping = { 'https://localhost/intersphinx/c/': inv_file, } diff --git a/tests/test_domain_cpp.py b/tests/test_domain_cpp.py index 93a43c754..8593c41f6 100644 --- a/tests/test_domain_cpp.py +++ b/tests/test_domain_cpp.py @@ -1366,7 +1366,7 @@ def test_domain_cpp_build_intersphinx(tempdir, app, status, warning): .. cpp:enum-class:: _enumClass .. cpp:function:: void _functionParam(int param) .. cpp:function:: template<typename TParam> void _templateParam() -""" # noqa +""" # noqa: F841 inv_file = tempdir / 'inventory' inv_file.write_bytes(b'''\ # Sphinx inventory version 2 @@ -1393,7 +1393,7 @@ _templateParam::TParam cpp:templateParam 1 index.html#_CPPv4I0E14_templateParamv _type cpp:type 1 index.html#_CPPv45$ - _union cpp:union 1 index.html#_CPPv46$ - _var cpp:member 1 index.html#_CPPv44$ - -''')) # noqa +''')) # noqa: W291 app.config.intersphinx_mapping = { 'https://localhost/intersphinx/cpp/': inv_file, } diff --git a/tests/test_ext_autodoc.py b/tests/test_ext_autodoc.py index 5bc12f7f5..09b7608b9 100644 --- a/tests/test_ext_autodoc.py +++ b/tests/test_ext_autodoc.py @@ -14,7 +14,7 @@ from docutils.statemachine import ViewList from sphinx import addnodes from sphinx.ext.autodoc import ALL, ModuleLevelDocumenter, Options from sphinx.ext.autodoc.directive import DocumenterBridge, process_documenter_options -from sphinx.testing.util import SphinxTestApp, Struct # NOQA +from sphinx.testing.util import SphinxTestApp, Struct # noqa: F401 from sphinx.util.docutils import LoggingReporter try: diff --git a/tests/test_ext_napoleon_docstring.py b/tests/test_ext_napoleon_docstring.py index c2704ebce..2919fa171 100644 --- a/tests/test_ext_napoleon_docstring.py +++ b/tests/test_ext_napoleon_docstring.py @@ -1172,7 +1172,7 @@ Methods: description -""" # NOQA +""" # noqa: W293 config = Config() actual = str(GoogleDocstring(docstring, config=config, app=None, what='module', options={'noindex': True})) diff --git a/tests/test_ext_napoleon_iterators.py b/tests/test_ext_napoleon_iterators.py index d587bd1ef..7ecdb138d 100644 --- a/tests/test_ext_napoleon_iterators.py +++ b/tests/test_ext_napoleon_iterators.py @@ -11,7 +11,7 @@ class ModuleIsDeprecatedTest(TestCase): def test_module_is_deprecated(self): sys.modules.pop("sphinx.ext.napoleon.iterators") with self.assertWarns(RemovedInSphinx70Warning): - import sphinx.ext.napoleon.iterators # noqa + import sphinx.ext.napoleon.iterators # noqa: F401 class BaseIteratorsTest(TestCase): diff --git a/tests/typing_test_data.py b/tests/typing_test_data.py index 6cbd7fb07..26f619fdc 100644 --- a/tests/typing_test_data.py +++ b/tests/typing_test_data.py @@ -77,7 +77,7 @@ def f14() -> Any: pass -def f15(x: "Unknown", y: "int") -> Any: # type: ignore # NOQA +def f15(x: "Unknown", y: "int") -> Any: # noqa: F821 # type: ignore pass |