From ab184ac20d82d0546c21f33d2fdfbfb324078d56 Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Sun, 29 Dec 2019 23:56:30 +0900 Subject: [PATCH] mypy: Enable disallow_incomplete_defs flag for type checking --- setup.cfg | 1 + sphinx/addnodes.py | 4 ++- sphinx/application.py | 15 +++++----- sphinx/builders/__init__.py | 4 +-- sphinx/builders/changes.py | 2 +- sphinx/builders/gettext.py | 4 +-- sphinx/builders/html.py | 4 +-- sphinx/builders/latex/__init__.py | 2 +- sphinx/builders/latex/transforms.py | 16 +++++----- sphinx/builders/manpage.py | 2 +- sphinx/builders/singlehtml.py | 4 +-- sphinx/builders/texinfo.py | 2 +- sphinx/config.py | 2 +- sphinx/domains/__init__.py | 2 +- sphinx/domains/citation.py | 4 +-- sphinx/domains/cpp.py | 2 +- sphinx/domains/std.py | 2 +- sphinx/environment/adapters/toctree.py | 6 ++-- sphinx/events.py | 4 +-- sphinx/ext/autodoc/__init__.py | 26 ++++++++-------- sphinx/ext/autodoc/mock.py | 6 ++-- sphinx/ext/autosummary/generate.py | 2 +- sphinx/ext/coverage.py | 2 +- sphinx/ext/duration.py | 4 +-- sphinx/ext/napoleon/__init__.py | 2 +- sphinx/ext/napoleon/iterators.py | 4 +-- sphinx/extension.py | 2 +- sphinx/highlighting.py | 4 +-- sphinx/io.py | 8 ++--- sphinx/jinja2glue.py | 2 +- sphinx/locale/__init__.py | 2 +- sphinx/pycode/parser.py | 2 +- sphinx/registry.py | 11 +++---- sphinx/testing/path.py | 8 ++--- sphinx/testing/util.py | 6 ++-- sphinx/transforms/__init__.py | 30 +++++++++---------- sphinx/transforms/compact_bullet_list.py | 2 +- sphinx/transforms/i18n.py | 6 ++-- sphinx/transforms/post_transforms/__init__.py | 8 ++--- sphinx/transforms/post_transforms/code.py | 4 +-- sphinx/transforms/post_transforms/compat.py | 2 +- sphinx/transforms/post_transforms/images.py | 2 +- sphinx/transforms/references.py | 6 ++-- sphinx/util/__init__.py | 2 +- sphinx/util/compat.py | 2 +- sphinx/util/docutils.py | 6 ++-- sphinx/util/inspect.py | 2 +- sphinx/util/jsonimpl.py | 8 ++--- sphinx/util/logging.py | 4 +-- sphinx/util/nodes.py | 2 +- sphinx/util/osutil.py | 2 +- sphinx/util/requests.py | 8 ++--- sphinx/versioning.py | 2 +- sphinx/writers/html.py | 4 +-- sphinx/writers/html5.py | 4 +-- sphinx/writers/manpage.py | 4 +-- sphinx/writers/text.py | 6 ++-- sphinx/writers/xml.py | 4 ++- 58 files changed, 151 insertions(+), 142 deletions(-) diff --git a/setup.cfg b/setup.cfg index 1f5bbd1cd..fdd2fe327 100644 --- a/setup.cfg +++ b/setup.cfg @@ -40,6 +40,7 @@ paths = . [mypy] +disallow_incomplete_defs = True show_column_numbers = True show_error_context = True ignore_missing_imports = True diff --git a/sphinx/addnodes.py b/sphinx/addnodes.py index baee2dada..a22391a6e 100644 --- a/sphinx/addnodes.py +++ b/sphinx/addnodes.py @@ -12,6 +12,7 @@ import warnings from typing import Any, Dict, List, Sequence from docutils import nodes +from docutils.nodes import Node from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning @@ -358,7 +359,8 @@ class abbreviation(nodes.abbreviation): .. deprecated:: 2.0 """ - def __init__(self, rawsource: str = '', text: str = '', *children, **attributes) -> None: + def __init__(self, rawsource: str = '', text: str = '', + *children: Node, **attributes: Any) -> None: warnings.warn("abbrevition node for Sphinx was replaced by docutils'.", RemovedInSphinx40Warning, stacklevel=2) diff --git a/sphinx/application.py b/sphinx/application.py index 975dc2a70..0520bc6f7 100644 --- a/sphinx/application.py +++ b/sphinx/application.py @@ -438,7 +438,7 @@ class Sphinx: logger.debug('[app] disconnecting event: [id=%s]', listener_id) self.events.disconnect(listener_id) - def emit(self, event: str, *args) -> List: + def emit(self, event: str, *args: Any) -> List: """Emit *event* and pass *arguments* to the callback functions. Return the return values of all callbacks as a list. Do not emit core @@ -446,7 +446,7 @@ class Sphinx: """ return self.events.emit(event, *args) - def emit_firstresult(self, event: str, *args) -> Any: + def emit_firstresult(self, event: str, *args: Any) -> Any: """Emit *event* and pass *arguments* to the callback functions. Return the result of the first callback that doesn't return ``None``. @@ -524,7 +524,8 @@ class Sphinx: """ self.registry.add_translator(name, translator_class, override=override) - def add_node(self, node: "Type[Element]", override: bool = False, **kwds) -> None: + def add_node(self, node: "Type[Element]", override: bool = False, + **kwds: Tuple[Callable, Callable]) -> None: """Register a Docutils node class. This is necessary for Docutils internals. It may also be used in the @@ -564,7 +565,7 @@ class Sphinx: def add_enumerable_node(self, node: "Type[Element]", figtype: str, title_getter: TitleGetter = None, override: bool = False, - **kwds) -> None: + **kwds: Tuple[Callable, Callable]) -> None: """Register a Docutils node class as a numfig target. Sphinx numbers the node automatically. And then the users can refer it @@ -600,7 +601,7 @@ class Sphinx: def add_directive(self, name: str, obj: Any, content: bool = None, arguments: Tuple[int, int, bool] = None, override: bool = False, - **options) -> None: + **options: Any) -> None: """Register a Docutils directive. *name* must be the prospective directive name. There are two possible @@ -729,7 +730,7 @@ class Sphinx: def add_directive_to_domain(self, domain: str, name: str, obj: Any, has_content: bool = None, argument_spec: Any = None, - override: bool = False, **option_spec) -> None: + override: bool = False, **option_spec: Any) -> None: """Register a Docutils directive in a domain. Like :meth:`add_directive`, but the directive is added to the domain @@ -1099,7 +1100,7 @@ class Sphinx: """ self.registry.add_source_suffix(suffix, filetype, override=override) - def add_source_parser(self, *args, **kwargs) -> None: + def add_source_parser(self, *args: Any, **kwargs: Any) -> None: """Register a parser class. .. versionadded:: 1.4 diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py index 777536d3e..0c858e315 100644 --- a/sphinx/builders/__init__.py +++ b/sphinx/builders/__init__.py @@ -118,11 +118,11 @@ class Builder: self.env.set_versioning_method(self.versioning_method, self.versioning_compare) - def get_translator_class(self, *args) -> "Type[nodes.NodeVisitor]": + def get_translator_class(self, *args: Any) -> "Type[nodes.NodeVisitor]": """Return a class of translator.""" return self.app.registry.get_translator_class(self) - def create_translator(self, *args) -> nodes.NodeVisitor: + def create_translator(self, *args: Any) -> nodes.NodeVisitor: """Return an instance of translator. This method returns an instance of ``default_translator_class`` by default. diff --git a/sphinx/builders/changes.py b/sphinx/builders/changes.py index a42215fad..c39e93518 100644 --- a/sphinx/builders/changes.py +++ b/sphinx/builders/changes.py @@ -50,7 +50,7 @@ class ChangesBuilder(Builder): 'deprecated': 'deprecated', } - def write(self, *ignored) -> None: + def write(self, *ignored: Any) -> None: version = self.config.version domain = cast(ChangeSetDomain, self.env.get_domain('changeset')) libchanges = {} # type: Dict[str, List[Tuple[str, str, int]]] diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py index e7adb0b8c..bbc1422e5 100644 --- a/sphinx/builders/gettext.py +++ b/sphinx/builders/gettext.py @@ -198,7 +198,7 @@ if source_date_epoch is not None: class LocalTimeZone(tzinfo): - def __init__(self, *args, **kw) -> None: + def __init__(self, *args: Any, **kw: Any) -> None: super().__init__(*args, **kw) # type: ignore self.tzdelta = tzdelta @@ -212,7 +212,7 @@ class LocalTimeZone(tzinfo): ltz = LocalTimeZone() -def should_write(filepath: str, new_content: str): +def should_write(filepath: str, new_content: str) -> bool: if not path.exists(filepath): return True try: diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py index 20502f467..38fbb2441 100644 --- a/sphinx/builders/html.py +++ b/sphinx/builders/html.py @@ -887,7 +887,7 @@ class StandaloneHTMLBuilder(Builder): indexer_name, indexer_name), RemovedInSphinx40Warning) - def _get_local_toctree(self, docname: str, collapse: bool = True, **kwds) -> str: + def _get_local_toctree(self, docname: str, collapse: bool = True, **kwds: Any) -> str: if 'includehidden' not in kwds: kwds['includehidden'] = False return self.render_partial(TocTree(self.env).get_toctree_for( @@ -1000,7 +1000,7 @@ class StandaloneHTMLBuilder(Builder): return False ctx['hasdoc'] = hasdoc - def warn(*args, **kwargs) -> str: + def warn(*args: Any, **kwargs: Any) -> str: """Simple warn() wrapper for themes.""" warnings.warn('The template function warn() was deprecated. ' 'Use warning() instead.', diff --git a/sphinx/builders/latex/__init__.py b/sphinx/builders/latex/__init__.py index 8111044d5..8b3864f25 100644 --- a/sphinx/builders/latex/__init__.py +++ b/sphinx/builders/latex/__init__.py @@ -216,7 +216,7 @@ class LaTeXBuilder(Builder): '[2016/05/29 stylesheet for highlighting with pygments]\n\n') f.write(highlighter.get_stylesheet()) - def write(self, *ignored) -> None: + def write(self, *ignored: Any) -> None: docwriter = LaTeXWriter(self) docsettings = OptionParser( defaults=self.env.settings, diff --git a/sphinx/builders/latex/transforms.py b/sphinx/builders/latex/transforms.py index 9fe44bc95..409b6c322 100644 --- a/sphinx/builders/latex/transforms.py +++ b/sphinx/builders/latex/transforms.py @@ -32,7 +32,7 @@ class FootnoteDocnameUpdater(SphinxTransform): default_priority = 700 TARGET_NODES = (nodes.footnote, nodes.footnote_reference) - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: matcher = NodeMatcher(*self.TARGET_NODES) for node in self.document.traverse(matcher): # type: nodes.Element node['docname'] = self.env.docname @@ -51,7 +51,7 @@ class ShowUrlsTransform(SphinxPostTransform): # references are expanded to footnotes (or not) expanded = False - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: try: # replace id_prefix temporarily settings = self.document.settings # type: Any @@ -338,7 +338,7 @@ class LaTeXFootnoteTransform(SphinxPostTransform): default_priority = 600 builders = ('latex',) - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: footnotes = list(self.document.traverse(nodes.footnote)) for node in footnotes: node.parent.remove(node) @@ -490,7 +490,7 @@ class BibliographyTransform(SphinxPostTransform): default_priority = 750 builders = ('latex',) - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: citations = thebibliography() for node in self.document.traverse(nodes.citation): node.parent.remove(node) @@ -509,7 +509,7 @@ class CitationReferenceTransform(SphinxPostTransform): default_priority = 5 # before ReferencesResolver builders = ('latex',) - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: domain = cast(CitationDomain, self.env.get_domain('citation')) matcher = NodeMatcher(addnodes.pending_xref, refdomain='citation', reftype='ref') for node in self.document.traverse(matcher): # type: addnodes.pending_xref @@ -529,7 +529,7 @@ class MathReferenceTransform(SphinxPostTransform): default_priority = 5 # before ReferencesResolver builders = ('latex',) - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: equations = self.env.get_domain('math').data['objects'] for node in self.document.traverse(addnodes.pending_xref): if node['refdomain'] == 'math' and node['reftype'] in ('eq', 'numref'): @@ -544,7 +544,7 @@ class LiteralBlockTransform(SphinxPostTransform): default_priority = 400 builders = ('latex',) - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: matcher = NodeMatcher(nodes.container, literal_block=True) for node in self.document.traverse(matcher): # type: nodes.container newnode = captioned_literal_block('', *node.children, **node.attributes) @@ -556,7 +556,7 @@ class DocumentTargetTransform(SphinxPostTransform): default_priority = 400 builders = ('latex',) - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: for node in self.document.traverse(addnodes.start_of_file): section = node.next_node(nodes.section) if section: diff --git a/sphinx/builders/manpage.py b/sphinx/builders/manpage.py index 94b312e36..432ae0afa 100644 --- a/sphinx/builders/manpage.py +++ b/sphinx/builders/manpage.py @@ -56,7 +56,7 @@ class ManualPageBuilder(Builder): raise NoUri @progress_message(__('writing')) - def write(self, *ignored) -> None: + def write(self, *ignored: Any) -> None: docwriter = ManualPageWriter(self) docsettings = OptionParser( defaults=self.env.settings, diff --git a/sphinx/builders/singlehtml.py b/sphinx/builders/singlehtml.py index 3309b024c..bf9b72d26 100644 --- a/sphinx/builders/singlehtml.py +++ b/sphinx/builders/singlehtml.py @@ -67,7 +67,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): if hashindex >= 0: refnode['refuri'] = fname + refuri[hashindex:] - def _get_local_toctree(self, docname: str, collapse: bool = True, **kwds) -> str: + def _get_local_toctree(self, docname: str, collapse: bool = True, **kwds: Any) -> str: if 'includehidden' not in kwds: kwds['includehidden'] = False toctree = TocTree(self.env).get_toctree_for(docname, self, collapse, **kwds) @@ -149,7 +149,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): 'display_toc': display_toc, } - def write(self, *ignored) -> None: + def write(self, *ignored: Any) -> None: docnames = self.env.all_docs with progress_message(__('preparing documents')): diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py index 16f81c666..ac697f563 100644 --- a/sphinx/builders/texinfo.py +++ b/sphinx/builders/texinfo.py @@ -90,7 +90,7 @@ class TexinfoBuilder(Builder): docname = docname[:-5] self.titles.append((docname, entry[2])) - def write(self, *ignored) -> None: + def write(self, *ignored: Any) -> None: self.init_document_data() for entry in self.document_data: docname, targetname, title, author = entry[:4] diff --git a/sphinx/config.py b/sphinx/config.py index 646034b31..0f022a039 100644 --- a/sphinx/config.py +++ b/sphinx/config.py @@ -154,7 +154,7 @@ class Config: 'env', []), } # type: Dict[str, Tuple] - def __init__(self, *args) -> None: + def __init__(self, *args: Any) -> None: if len(args) == 4: # old style arguments: (dirname, filename, overrides, tags) warnings.warn('The argument of Config() class has been changed. ' diff --git a/sphinx/domains/__init__.py b/sphinx/domains/__init__.py index a2109d3f7..886dbb876 100644 --- a/sphinx/domains/__init__.py +++ b/sphinx/domains/__init__.py @@ -48,7 +48,7 @@ class ObjType: 'searchprio': 1, } - def __init__(self, lname: str, *roles, **attrs) -> None: + def __init__(self, lname: str, *roles: Any, **attrs: Any) -> None: self.lname = lname self.roles = roles # type: Tuple self.attrs = self.known_attrs.copy() # type: Dict diff --git a/sphinx/domains/citation.py b/sphinx/domains/citation.py index 0b512c365..c6b0810df 100644 --- a/sphinx/domains/citation.py +++ b/sphinx/domains/citation.py @@ -112,7 +112,7 @@ class CitationDefinitionTransform(SphinxTransform): """Mark citation definition labels as not smartquoted.""" default_priority = 619 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: domain = cast(CitationDomain, self.env.get_domain('citation')) for node in self.document.traverse(nodes.citation): # register citation node to domain @@ -131,7 +131,7 @@ class CitationReferenceTransform(SphinxTransform): """ default_priority = 619 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: domain = cast(CitationDomain, self.env.get_domain('citation')) for node in self.document.traverse(nodes.citation_reference): target = node.astext() diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py index b7f74266c..fdadfe00c 100644 --- a/sphinx/domains/cpp.py +++ b/sphinx/domains/cpp.py @@ -6496,7 +6496,7 @@ class AliasNode(nodes.Element): class AliasTransform(SphinxTransform): default_priority = ReferencesResolver.default_priority - 1 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(AliasNode): class Warner: def warn(self, msg): diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py index 705cf175c..f8da0decb 100644 --- a/sphinx/domains/std.py +++ b/sphinx/domains/std.py @@ -628,7 +628,7 @@ class StandardDomain(Domain): self.progoptions[program, name] = (docname, labelid) def build_reference_node(self, fromdocname: str, builder: "Builder", docname: str, - labelid: str, sectname: str, rolename: str, **options + labelid: str, sectname: str, rolename: str, **options: Any ) -> Element: nodeclass = options.pop('nodeclass', nodes.reference) newnode = nodeclass('', '', internal=True, **options) diff --git a/sphinx/environment/adapters/toctree.py b/sphinx/environment/adapters/toctree.py index 0975b33cd..b933f43bd 100644 --- a/sphinx/environment/adapters/toctree.py +++ b/sphinx/environment/adapters/toctree.py @@ -8,8 +8,8 @@ :license: BSD, see LICENSE for details. """ +from typing import Any, Iterable, List from typing import cast -from typing import Iterable, List from docutils import nodes from docutils.nodes import Element, Node @@ -314,8 +314,8 @@ class TocTree: node['refuri'] = node['anchorname'] or '#' return toc - def get_toctree_for(self, docname: str, builder: "Builder", collapse: bool, **kwds - ) -> Element: + def get_toctree_for(self, docname: str, builder: "Builder", collapse: bool, + **kwds: Any) -> Element: """Return the global TOC nodetree.""" doctree = self.env.get_doctree(self.env.config.master_doc) toctrees = [] # type: List[Element] diff --git a/sphinx/events.py b/sphinx/events.py index 52a87439b..288274f33 100644 --- a/sphinx/events.py +++ b/sphinx/events.py @@ -81,7 +81,7 @@ class EventManager: for event in self.listeners.values(): event.pop(listener_id, None) - def emit(self, name: str, *args) -> List: + def emit(self, name: str, *args: Any) -> List: """Emit a Sphinx event.""" try: logger.debug('[app] emitting event: %r%s', name, repr(args)[:100]) @@ -99,7 +99,7 @@ class EventManager: results.append(callback(self.app, *args)) return results - def emit_firstresult(self, name: str, *args) -> Any: + def emit_firstresult(self, name: str, *args: Any) -> Any: """Emit a Sphinx event and returns first result. This returns the result of the first handler that doesn't return ``None``. diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py index c053b5b75..03bbb5f1d 100644 --- a/sphinx/ext/autodoc/__init__.py +++ b/sphinx/ext/autodoc/__init__.py @@ -221,7 +221,7 @@ class Documenter: option_spec = {'noindex': bool_option} # type: Dict[str, Callable] - def get_attr(self, obj: Any, name: str, *defargs) -> Any: + def get_attr(self, obj: Any, name: str, *defargs: Any) -> Any: """getattr() override for types such as Zope interfaces.""" return autodoc_attrgetter(self.env.app, obj, name, *defargs) @@ -351,7 +351,7 @@ class Documenter: return False return True - def format_args(self, **kwargs) -> str: + def format_args(self, **kwargs: Any) -> str: """Format the argument signature of *self.object*. Should return None if the object does not have a signature. @@ -369,7 +369,7 @@ class Documenter: # directives of course) return '.'.join(self.objpath) or self.modname - def format_signature(self, **kwargs) -> str: + def format_signature(self, **kwargs: Any) -> str: """Format the signature (arguments and return annotation) of the object. Let the user process it via the ``autodoc-process-signature`` event. @@ -750,7 +750,7 @@ class ModuleDocumenter(Documenter): 'imported-members': bool_option, 'ignore-module-all': bool_option } # type: Dict[str, Callable] - def __init__(self, *args) -> None: + def __init__(self, *args: Any) -> None: super().__init__(*args) merge_special_members_option(self.options) @@ -928,7 +928,7 @@ class DocstringSignatureMixin: return lines return super().get_doc(None, ignore) # type: ignore - def format_signature(self, **kwargs) -> str: + def format_signature(self, **kwargs: Any) -> str: if self.args is None and self.env.config.autodoc_docstring_signature: # type: ignore # only act if a signature is not explicitly given already, and if # the feature is enabled @@ -943,7 +943,7 @@ class DocstringStripSignatureMixin(DocstringSignatureMixin): Mixin for AttributeDocumenter to provide the feature of stripping any function signature from the docstring. """ - def format_signature(self, **kwargs) -> str: + def format_signature(self, **kwargs: Any) -> str: if self.args is None and self.env.config.autodoc_docstring_signature: # type: ignore # only act if a signature is not explicitly given already, and if # the feature is enabled @@ -970,7 +970,7 @@ class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # typ return (inspect.isfunction(member) or inspect.isbuiltin(member) or (inspect.isroutine(member) and isinstance(parent, ModuleDocumenter))) - def format_args(self, **kwargs) -> str: + def format_args(self, **kwargs: Any) -> str: if self.env.config.autodoc_typehints == 'none': kwargs.setdefault('show_annotation', False) @@ -1047,7 +1047,7 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type: 'private-members': bool_option, 'special-members': members_option, } # type: Dict[str, Callable] - def __init__(self, *args) -> None: + def __init__(self, *args: Any) -> None: super().__init__(*args) merge_special_members_option(self.options) @@ -1067,7 +1067,7 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type: self.doc_as_attr = True return ret - def format_args(self, **kwargs) -> str: + def format_args(self, **kwargs: Any) -> str: if self.env.config.autodoc_typehints == 'none': kwargs.setdefault('show_annotation', False) @@ -1087,7 +1087,7 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type: # with __init__ in C return None - def format_signature(self, **kwargs) -> str: + def format_signature(self, **kwargs: Any) -> str: if self.doc_as_attr: return '' @@ -1275,7 +1275,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type: return ret - def format_args(self, **kwargs) -> str: + def format_args(self, **kwargs: Any) -> str: if self.env.config.autodoc_typehints == 'none': kwargs.setdefault('show_annotation', False) @@ -1290,7 +1290,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type: args = args.replace('\\', '\\\\') return args - def add_directive_header(self, sig) -> None: + def add_directive_header(self, sig: str) -> None: super().add_directive_header(sig) sourcename = self.get_sourcename() @@ -1492,7 +1492,7 @@ def get_documenters(app: Sphinx) -> Dict[str, "Type[Documenter]"]: return app.registry.documenters -def autodoc_attrgetter(app: Sphinx, obj: Any, name: str, *defargs) -> Any: +def autodoc_attrgetter(app: Sphinx, obj: Any, name: str, *defargs: Any) -> Any: """Alternative getattr() for types""" for typ, func in app.registry.autodoc_attrgettrs.items(): if isinstance(obj, typ): diff --git a/sphinx/ext/autodoc/mock.py b/sphinx/ext/autodoc/mock.py index 7fa4627a6..055b706b1 100644 --- a/sphinx/ext/autodoc/mock.py +++ b/sphinx/ext/autodoc/mock.py @@ -28,7 +28,7 @@ class _MockObject: __display_name__ = '_MockObject' - def __new__(cls, *args, **kwargs) -> Any: + def __new__(cls, *args: Any, **kwargs: Any) -> Any: if len(args) == 3 and isinstance(args[1], tuple): superclass = args[1][-1].__class__ if superclass is cls: @@ -38,7 +38,7 @@ class _MockObject: return super().__new__(cls) - def __init__(self, *args, **kwargs) -> None: + def __init__(self, *args: Any, **kwargs: Any) -> None: self.__qualname__ = '' def __len__(self) -> int: @@ -59,7 +59,7 @@ class _MockObject: def __getattr__(self, key: str) -> "_MockObject": return _make_subclass(key, self.__display_name__, self.__class__)() - def __call__(self, *args, **kw) -> Any: + def __call__(self, *args: Any, **kw: Any) -> Any: if args and type(args[0]) in [type, FunctionType, MethodType]: # Appears to be a decorator, pass through unchanged return args[0] diff --git a/sphinx/ext/autosummary/generate.py b/sphinx/ext/autosummary/generate.py index 85cf841ed..1db927f9a 100644 --- a/sphinx/ext/autosummary/generate.py +++ b/sphinx/ext/autosummary/generate.py @@ -62,7 +62,7 @@ class DummyApplication: self._warncount = 0 self.warningiserror = False - def emit_firstresult(self, *args) -> None: + def emit_firstresult(self, *args: Any) -> None: pass diff --git a/sphinx/ext/coverage.py b/sphinx/ext/coverage.py index 7d53e7bb9..1bb914810 100644 --- a/sphinx/ext/coverage.py +++ b/sphinx/ext/coverage.py @@ -80,7 +80,7 @@ class CoverageBuilder(Builder): def get_outdated_docs(self) -> str: return 'coverage overview' - def write(self, *ignored) -> None: + def write(self, *ignored: Any) -> None: self.py_undoc = {} # type: Dict[str, Dict[str, Any]] self.build_py_coverage() self.write_py_coverage() diff --git a/sphinx/ext/duration.py b/sphinx/ext/duration.py index 1286e49ec..6308d569b 100644 --- a/sphinx/ext/duration.py +++ b/sphinx/ext/duration.py @@ -32,7 +32,7 @@ class DurationDomain(Domain): def reading_durations(self) -> Dict[str, timedelta]: return self.data.setdefault('reading_durations', {}) - def note_reading_duration(self, duration: timedelta): + def note_reading_duration(self, duration: timedelta) -> None: self.reading_durations[self.env.docname] = duration def clear(self) -> None: @@ -69,7 +69,7 @@ def on_doctree_read(app: Sphinx, doctree: nodes.document) -> None: domain.note_reading_duration(duration) -def on_build_finished(app: Sphinx, error): +def on_build_finished(app: Sphinx, error: Exception) -> None: """Display duration ranking on current build.""" domain = cast(DurationDomain, app.env.get_domain('duration')) durations = sorted(domain.reading_durations.items(), key=itemgetter(1), reverse=True) diff --git a/sphinx/ext/napoleon/__init__.py b/sphinx/ext/napoleon/__init__.py index d211a050e..25b8640d7 100644 --- a/sphinx/ext/napoleon/__init__.py +++ b/sphinx/ext/napoleon/__init__.py @@ -265,7 +265,7 @@ class Config: 'napoleon_custom_sections': (None, 'env') } - def __init__(self, **settings) -> None: + def __init__(self, **settings: Any) -> None: for name, (default, rebuild) in self._config_values.items(): setattr(self, name, default) for name, value in settings.items(): diff --git a/sphinx/ext/napoleon/iterators.py b/sphinx/ext/napoleon/iterators.py index 3aa728e44..2adbd431f 100644 --- a/sphinx/ext/napoleon/iterators.py +++ b/sphinx/ext/napoleon/iterators.py @@ -47,7 +47,7 @@ class peek_iter: be set to a new object instance: ``object()``. """ - def __init__(self, *args) -> None: + def __init__(self, *args: Any) -> None: """__init__(o, sentinel=None)""" self._iterable = iter(*args) # type: Iterable self._cache = collections.deque() # type: collections.deque @@ -208,7 +208,7 @@ class modify_iter(peek_iter): "whitespace." """ - def __init__(self, *args, **kwargs) -> None: + def __init__(self, *args: Any, **kwargs: Any) -> None: """__init__(o, sentinel=None, modifier=lambda x: x)""" if 'modifier' in kwargs: self.modifier = kwargs['modifier'] diff --git a/sphinx/extension.py b/sphinx/extension.py index 3cab20c2f..2b55eaa24 100644 --- a/sphinx/extension.py +++ b/sphinx/extension.py @@ -23,7 +23,7 @@ logger = logging.getLogger(__name__) class Extension: - def __init__(self, name: str, module: Any, **kwargs) -> None: + def __init__(self, name: str, module: Any, **kwargs: Any) -> None: self.name = name self.module = module self.metadata = kwargs diff --git a/sphinx/highlighting.py b/sphinx/highlighting.py index 694a41d61..14b56671a 100644 --- a/sphinx/highlighting.py +++ b/sphinx/highlighting.py @@ -93,7 +93,7 @@ class PygmentsBridge: else: return get_style_by_name(stylename) - def get_formatter(self, **kwargs) -> Formatter: + def get_formatter(self, **kwargs: Any) -> Formatter: kwargs.update(self.formatter_args) return self.formatter(**kwargs) @@ -155,7 +155,7 @@ class PygmentsBridge: return lexer def highlight_block(self, source: str, lang: str, opts: Dict = None, - force: bool = False, location: Any = None, **kwargs) -> str: + force: bool = False, location: Any = None, **kwargs: Any) -> str: if not isinstance(source, str): source = source.decode() diff --git a/sphinx/io.py b/sphinx/io.py index 4f354aace..8253f4a9c 100644 --- a/sphinx/io.py +++ b/sphinx/io.py @@ -59,7 +59,7 @@ class SphinxBaseReader(standalone.Reader): transforms = [] # type: List[Type[Transform]] - def __init__(self, *args, **kwargs) -> None: + def __init__(self, *args: Any, **kwargs: Any) -> None: from sphinx.application import Sphinx if len(args) > 0 and isinstance(args[0], Sphinx): self._app = args[0] @@ -181,7 +181,7 @@ class SphinxDummyWriter(UnfilteredWriter): pass -def SphinxDummySourceClass(source: Any, *args, **kwargs) -> Any: +def SphinxDummySourceClass(source: Any, *args: Any, **kwargs: Any) -> Any: """Bypass source object as is to cheat Publisher.""" return source @@ -192,7 +192,7 @@ class SphinxBaseFileInput(FileInput): It supports to replace unknown Unicode characters to '?'. """ - def __init__(self, app: "Sphinx", env: BuildEnvironment, *args, **kwds) -> None: + def __init__(self, app: "Sphinx", env: BuildEnvironment, *args: Any, **kwds: Any) -> None: self.app = app self.env = env @@ -210,7 +210,7 @@ class SphinxFileInput(FileInput): """A basic FileInput for Sphinx.""" supported = ('*',) # RemovedInSphinx30Warning - def __init__(self, *args, **kwargs) -> None: + def __init__(self, *args: Any, **kwargs: Any) -> None: kwargs['error_handler'] = 'sphinx' super().__init__(*args, **kwargs) diff --git a/sphinx/jinja2glue.py b/sphinx/jinja2glue.py index 060b9f1bd..826a57485 100644 --- a/sphinx/jinja2glue.py +++ b/sphinx/jinja2glue.py @@ -103,7 +103,7 @@ class idgen: @contextfunction -def warning(context: Dict, message: str, *args, **kwargs) -> str: +def warning(context: Dict, message: str, *args: Any, **kwargs: Any) -> str: if 'pagename' in context: filename = context.get('pagename') + context.get('file_suffix', '') message = 'in rendering %s: %s' % (filename, message) diff --git a/sphinx/locale/__init__.py b/sphinx/locale/__init__.py index a668c6a7f..262425a36 100644 --- a/sphinx/locale/__init__.py +++ b/sphinx/locale/__init__.py @@ -243,7 +243,7 @@ def get_translation(catalog, namespace='general'): .. versionadded:: 1.8 """ - def gettext(message: str, *args) -> 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 # NOQA diff --git a/sphinx/pycode/parser.py b/sphinx/pycode/parser.py index f3b8d1108..2c584ce1d 100644 --- a/sphinx/pycode/parser.py +++ b/sphinx/pycode/parser.py @@ -117,7 +117,7 @@ class Token: else: raise ValueError('Unknown value: %r' % other) - def match(self, *conditions) -> bool: + def match(self, *conditions: Any) -> bool: return any(self == candidate for candidate in conditions) def __repr__(self) -> str: diff --git a/sphinx/registry.py b/sphinx/registry.py index ffeaa555c..d7bffa2ce 100644 --- a/sphinx/registry.py +++ b/sphinx/registry.py @@ -184,7 +184,7 @@ class SphinxComponentRegistry: def add_directive_to_domain(self, domain: str, name: str, obj: Any, has_content: bool = None, argument_spec: Any = None, - override: bool = False, **option_spec) -> None: + override: bool = False, **option_spec: Any) -> None: logger.debug('[app] adding directive to domain: %r', (domain, name, obj, has_content, argument_spec, option_spec)) if domain not in self.domains: @@ -273,7 +273,7 @@ class SphinxComponentRegistry: else: self.source_suffix[suffix] = filetype - def add_source_parser(self, *args, **kwargs) -> None: + def add_source_parser(self, *args: Any, **kwargs: Any) -> None: logger.debug('[app] adding search source_parser: %r', args) if len(args) == 1: # new sytle arguments: (source_parser) @@ -352,7 +352,8 @@ class SphinxComponentRegistry: raise ExtensionError(__('Translator for %r already exists') % name) self.translators[name] = translator - def add_translation_handlers(self, node: "Type[Element]", **kwargs) -> None: + def add_translation_handlers(self, node: "Type[Element]", + **kwargs: Tuple[Callable, Callable]) -> None: logger.debug('[app] adding translation_handlers: %r, %r', node, kwargs) for builder_name, handlers in kwargs.items(): translation_handlers = self.translation_handlers.setdefault(builder_name, {}) @@ -361,13 +362,13 @@ class SphinxComponentRegistry: translation_handlers[node.__name__] = (visit, depart) except ValueError: raise ExtensionError(__('kwargs for add_node() must be a (visit, depart) ' - 'function tuple: %r=%r') % builder_name, handlers) + 'function tuple: %r=%r') % (builder_name, handlers)) def get_translator_class(self, builder: Builder) -> "Type[nodes.NodeVisitor]": return self.translators.get(builder.name, builder.default_translator_class) - def create_translator(self, builder: Builder, *args) -> nodes.NodeVisitor: + def create_translator(self, builder: Builder, *args: Any) -> nodes.NodeVisitor: translator_class = self.get_translator_class(builder) assert translator_class, "translator not found for %s" % builder.name translator = translator_class(*args) diff --git a/sphinx/testing/path.py b/sphinx/testing/path.py index d2fc4f31e..be3c74b37 100644 --- a/sphinx/testing/path.py +++ b/sphinx/testing/path.py @@ -124,17 +124,17 @@ class path(str): def utime(self, arg: Any) -> None: os.utime(self, arg) - def open(self, mode: str = 'r', **kwargs) -> IO: + def open(self, mode: str = 'r', **kwargs: Any) -> IO: return open(self, mode, **kwargs) - def write_text(self, text: str, encoding: str = 'utf-8', **kwargs) -> None: + def write_text(self, text: str, encoding: str = 'utf-8', **kwargs: Any) -> None: """ Writes the given `text` to the file. """ with open(self, 'w', encoding=encoding, **kwargs) as f: f.write(text) - def text(self, encoding: str = 'utf-8', **kwargs) -> str: + def text(self, encoding: str = 'utf-8', **kwargs: Any) -> str: """ Returns the text in the file. """ @@ -181,7 +181,7 @@ class path(str): """ os.makedirs(self, mode, exist_ok=exist_ok) - def joinpath(self, *args) -> "path": + def joinpath(self, *args: Any) -> "path": """ Joins the path with the argument given and returns the result. """ diff --git a/sphinx/testing/util.py b/sphinx/testing/util.py index 1ba3237c4..a031b2ad2 100644 --- a/sphinx/testing/util.py +++ b/sphinx/testing/util.py @@ -47,7 +47,7 @@ def assert_startswith(thing: str, prefix: str) -> None: assert False, '%r does not start with %r' % (thing, prefix) -def assert_node(node: nodes.Node, cls: Any = None, xpath: str = "", **kwargs) -> None: +def assert_node(node: nodes.Node, cls: Any = None, xpath: str = "", **kwargs: Any) -> None: if cls: if isinstance(cls, list): assert_node(node, cls[0], xpath=xpath, **kwargs) @@ -92,7 +92,7 @@ def etree_parse(path: str) -> Any: class Struct: - def __init__(self, **kwds) -> None: + def __init__(self, **kwds: Any) -> None: self.__dict__.update(kwds) @@ -165,7 +165,7 @@ class SphinxTestAppWrapperForSkipBuilding: def __getattr__(self, name: str) -> Any: return getattr(self.app, name) - def build(self, *args, **kw) -> None: + def build(self, *args: Any, **kw: Any) -> None: if not self.app.outdir.listdir(): # type: ignore # if listdir is empty, do build. self.app.build(*args, **kw) diff --git a/sphinx/transforms/__init__.py b/sphinx/transforms/__init__.py index df94aca49..58121bf59 100644 --- a/sphinx/transforms/__init__.py +++ b/sphinx/transforms/__init__.py @@ -104,7 +104,7 @@ class DefaultSubstitutions(SphinxTransform): # run before the default Substitutions default_priority = 210 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: # only handle those not otherwise defined in the document to_handle = default_substitutions - set(self.document.substitution_defs) for ref in self.document.traverse(nodes.substitution_reference): @@ -127,7 +127,7 @@ class MoveModuleTargets(SphinxTransform): """ default_priority = 210 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(nodes.target): if not node['ids']: continue @@ -145,7 +145,7 @@ class HandleCodeBlocks(SphinxTransform): """ default_priority = 210 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: # move doctest blocks out of blockquotes for node in self.document.traverse(nodes.block_quote): if all(isinstance(child, nodes.doctest_block) for child @@ -169,7 +169,7 @@ class AutoNumbering(SphinxTransform): """ default_priority = 210 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: domain = self.env.get_domain('std') # type: StandardDomain for node in self.document.traverse(nodes.Element): @@ -183,7 +183,7 @@ class SortIds(SphinxTransform): """ default_priority = 261 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(nodes.section): if len(node['ids']) > 1 and node['ids'][0].startswith('id'): node['ids'] = node['ids'][1:] + [node['ids'][0]] @@ -204,7 +204,7 @@ class ApplySourceWorkaround(SphinxTransform): """ default_priority = 10 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(): # type: Node if isinstance(node, (nodes.TextElement, nodes.image)): apply_source_workaround(node) @@ -216,7 +216,7 @@ class AutoIndexUpgrader(SphinxTransform): """ default_priority = 210 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(addnodes.index): if 'entries' in node and any(len(entry) == 4 for entry in node['entries']): msg = __('4 column based index found. ' @@ -233,7 +233,7 @@ class ExtraTranslatableNodes(SphinxTransform): """ default_priority = 10 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: targets = self.config.gettext_additional_targets target_nodes = [v for k, v in TRANSLATABLE_NODES.items() if k in targets] if not target_nodes: @@ -252,7 +252,7 @@ class UnreferencedFootnotesDetector(SphinxTransform): """ default_priority = 200 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.footnotes: if node['names'] == []: # footnote having duplicated number. It is already warned at parser. @@ -273,7 +273,7 @@ class DoctestTransform(SphinxTransform): """Set "doctest" style to each doctest_block node""" default_priority = 500 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(nodes.doctest_block): node['classes'].append('doctest') @@ -284,7 +284,7 @@ class FigureAligner(SphinxTransform): """ default_priority = 700 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: matcher = NodeMatcher(nodes.table, nodes.figure) for node in self.document.traverse(matcher): # type: Element node.setdefault('align', 'default') @@ -294,7 +294,7 @@ class FilterSystemMessages(SphinxTransform): """Filter system messages from a doctree.""" default_priority = 999 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: filterlevel = 2 if self.config.keep_warnings else 5 for node in self.document.traverse(nodes.system_message): if node['level'] < filterlevel: @@ -321,7 +321,7 @@ class SphinxSmartQuotes(SmartQuotes, SphinxTransform): """ default_priority = 750 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: if not self.is_available(): return @@ -370,7 +370,7 @@ class DoctreeReadEvent(SphinxTransform): """Emit :event:`doctree-read` event.""" default_priority = 880 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: self.app.emit('doctree-read', self.document) @@ -378,7 +378,7 @@ class ManpageLink(SphinxTransform): """Find manpage section numbers and names""" default_priority = 999 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(addnodes.manpage): manpage = ' '.join([str(x) for x in node.children if isinstance(x, nodes.Text)]) diff --git a/sphinx/transforms/compact_bullet_list.py b/sphinx/transforms/compact_bullet_list.py index 09274cd5f..a1a95003c 100644 --- a/sphinx/transforms/compact_bullet_list.py +++ b/sphinx/transforms/compact_bullet_list.py @@ -61,7 +61,7 @@ class RefOnlyBulletListTransform(SphinxTransform): """ default_priority = 100 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: if self.config.html_compact_lists: return diff --git a/sphinx/transforms/i18n.py b/sphinx/transforms/i18n.py index d1c125a7e..e6870e6ca 100644 --- a/sphinx/transforms/i18n.py +++ b/sphinx/transforms/i18n.py @@ -84,7 +84,7 @@ class PreserveTranslatableMessages(SphinxTransform): """ default_priority = 10 # this MUST be invoked before Locale transform - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(addnodes.translatable): node.preserve_original_messages() @@ -95,7 +95,7 @@ class Locale(SphinxTransform): """ default_priority = 20 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: settings, source = self.document.settings, self.document['source'] msgstr = '' @@ -480,7 +480,7 @@ class RemoveTranslatableInline(SphinxTransform): """ default_priority = 999 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: from sphinx.builders.gettext import MessageCatalogBuilder if isinstance(self.app.builder, MessageCatalogBuilder): return diff --git a/sphinx/transforms/post_transforms/__init__.py b/sphinx/transforms/post_transforms/__init__.py index 9cb7add44..c7d521bca 100644 --- a/sphinx/transforms/post_transforms/__init__.py +++ b/sphinx/transforms/post_transforms/__init__.py @@ -38,7 +38,7 @@ class SphinxPostTransform(SphinxTransform): builders = () # type: Tuple[str, ...] formats = () # type: Tuple[str, ...] - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: if self.is_supported(): self.run(**kwargs) @@ -51,7 +51,7 @@ class SphinxPostTransform(SphinxTransform): return True - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: """main method of post transforms. Subclasses should override this method instead of ``apply()``. @@ -66,7 +66,7 @@ class ReferencesResolver(SphinxPostTransform): default_priority = 10 - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: for node in self.document.traverse(addnodes.pending_xref): contnode = cast(nodes.TextElement, node[0].deepcopy()) newnode = None @@ -178,7 +178,7 @@ class ReferencesResolver(SphinxPostTransform): class OnlyNodeTransform(SphinxPostTransform): default_priority = 50 - def run(self, **kwargs) -> None: + def run(self, **kwargs: Any) -> None: # A comment on the comment() nodes being inserted: replacing by [] would # result in a "Losing ids" exception if there is a target node before # the only node, so we make sure docutils can transfer the id to diff --git a/sphinx/transforms/post_transforms/code.py b/sphinx/transforms/post_transforms/code.py index 0707b85a8..06f687ea1 100644 --- a/sphinx/transforms/post_transforms/code.py +++ b/sphinx/transforms/post_transforms/code.py @@ -36,7 +36,7 @@ class HighlightLanguageTransform(SphinxTransform): """ default_priority = 400 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: visitor = HighlightLanguageVisitor(self.document, self.config.highlight_language) self.document.walkabout(visitor) @@ -92,7 +92,7 @@ class TrimDoctestFlagsTransform(SphinxTransform): """ default_priority = HighlightLanguageTransform.default_priority + 1 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: if not self.config.trim_doctest_flags: return diff --git a/sphinx/transforms/post_transforms/compat.py b/sphinx/transforms/post_transforms/compat.py index 4520cf4fc..e12923e79 100644 --- a/sphinx/transforms/post_transforms/compat.py +++ b/sphinx/transforms/post_transforms/compat.py @@ -33,7 +33,7 @@ class MathNodeMigrator(SphinxTransform): """ default_priority = 999 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for math_node in self.document.traverse(nodes.math): # case: old styled ``math`` node generated by old extensions if len(math_node) == 0: diff --git a/sphinx/transforms/post_transforms/images.py b/sphinx/transforms/post_transforms/images.py index 69a939731..10463bcac 100644 --- a/sphinx/transforms/post_transforms/images.py +++ b/sphinx/transforms/post_transforms/images.py @@ -183,7 +183,7 @@ class ImageConverter(BaseImageConverter): #: ] conversion_rules = [] # type: List[Tuple[str, str]] - def __init__(self, *args, **kwargs) -> None: + def __init__(self, *args: Any, **kwargs: Any) -> None: self.available = None # type: bool # the converter is available or not. # Will be checked at first conversion diff --git a/sphinx/transforms/references.py b/sphinx/transforms/references.py index 79b439f4b..4b89e104d 100644 --- a/sphinx/transforms/references.py +++ b/sphinx/transforms/references.py @@ -26,7 +26,7 @@ class SubstitutionDefinitionsRemover(SphinxTransform): # should be invoked after Substitutions process default_priority = Substitutions.default_priority + 1 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(nodes.substitution_definition): node.parent.remove(node) @@ -34,7 +34,7 @@ class SubstitutionDefinitionsRemover(SphinxTransform): class SphinxDanglingReferences(DanglingReferences): """DanglingReferences transform which does not output info messages.""" - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: try: reporter = self.document.reporter report_level = reporter.report_level @@ -50,7 +50,7 @@ class SphinxDomains(SphinxTransform): """Collect objects to Sphinx domains for cross references.""" default_priority = 850 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for domain in self.env.domains.values(): domain.process_doc(self.env, self.env.docname, self.document) diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py index 5829d47df..2ee286703 100644 --- a/sphinx/util/__init__.py +++ b/sphinx/util/__init__.py @@ -482,7 +482,7 @@ def force_decode(string: str, encoding: str) -> str: class attrdict(dict): - def __init__(self, *args, **kwargs) -> None: + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) warnings.warn('The attrdict class is deprecated.', RemovedInSphinx40Warning, stacklevel=2) diff --git a/sphinx/util/compat.py b/sphinx/util/compat.py index 75ef90350..1030d5533 100644 --- a/sphinx/util/compat.py +++ b/sphinx/util/compat.py @@ -53,7 +53,7 @@ class IndexEntriesMigrator(SphinxTransform): """Migrating indexentries from old style (4columns) to new style (5columns).""" default_priority = 700 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: for node in self.document.traverse(addnodes.index): for i, entries in enumerate(node['entries']): if len(entries) == 4: diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py index 233c1a2aa..564313505 100644 --- a/sphinx/util/docutils.py +++ b/sphinx/util/docutils.py @@ -279,7 +279,9 @@ def is_html5_writer_available() -> bool: return __version_info__ > (0, 13, 0) -def directive_helper(obj: Any, has_content: bool = None, argument_spec: Tuple[int, int, bool] = None, **option_spec) -> Any: # NOQA +def directive_helper(obj: Any, has_content: bool = None, + argument_spec: Tuple[int, int, bool] = None, **option_spec: Any + ) -> Any: warnings.warn('function based directive support is now deprecated. ' 'Use class based directive instead.', RemovedInSphinx30Warning) @@ -317,7 +319,7 @@ def switch_source_input(state: State, content: StringList) -> Generator[None, No class SphinxFileOutput(FileOutput): """Better FileOutput class for Sphinx.""" - def __init__(self, **kwargs) -> None: + def __init__(self, **kwargs: Any) -> None: self.overwrite_if_changed = kwargs.pop('overwrite_if_changed', False) super().__init__(**kwargs) diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py index 20af75628..4092dd360 100644 --- a/sphinx/util/inspect.py +++ b/sphinx/util/inspect.py @@ -224,7 +224,7 @@ def isproperty(obj: Any) -> bool: return isinstance(obj, property) -def safe_getattr(obj: Any, name: str, *defargs) -> Any: +def safe_getattr(obj: Any, name: str, *defargs: Any) -> Any: """A getattr() that turns all exceptions into AttributeErrors.""" try: return getattr(obj, name, *defargs) diff --git a/sphinx/util/jsonimpl.py b/sphinx/util/jsonimpl.py index c5336a195..404ea4b02 100644 --- a/sphinx/util/jsonimpl.py +++ b/sphinx/util/jsonimpl.py @@ -28,19 +28,19 @@ class SphinxJSONEncoder(json.JSONEncoder): return super().default(obj) -def dump(obj: Any, fp: IO, *args, **kwds) -> None: +def dump(obj: Any, fp: IO, *args: Any, **kwds: Any) -> None: kwds['cls'] = SphinxJSONEncoder json.dump(obj, fp, *args, **kwds) -def dumps(obj: Any, *args, **kwds) -> str: +def dumps(obj: Any, *args: Any, **kwds: Any) -> str: kwds['cls'] = SphinxJSONEncoder return json.dumps(obj, *args, **kwds) -def load(*args, **kwds) -> Any: +def load(*args: Any, **kwds: Any) -> Any: return json.load(*args, **kwds) -def loads(*args, **kwds) -> Any: +def loads(*args: Any, **kwds: Any) -> Any: return json.loads(*args, **kwds) diff --git a/sphinx/util/logging.py b/sphinx/util/logging.py index 60a409093..73d89021c 100644 --- a/sphinx/util/logging.py +++ b/sphinx/util/logging.py @@ -119,14 +119,14 @@ class SphinxWarningLogRecord(SphinxLogRecord): class SphinxLoggerAdapter(logging.LoggerAdapter): """LoggerAdapter allowing ``type`` and ``subtype`` keywords.""" - def log(self, level: Union[int, str], msg: str, *args, **kwargs) -> None: + def log(self, level: Union[int, str], msg: str, *args: Any, **kwargs: Any) -> None: if isinstance(level, int): super().log(level, msg, *args, **kwargs) else: levelno = LEVEL_NAMES[level] super().log(levelno, msg, *args, **kwargs) - def verbose(self, msg: str, *args, **kwargs) -> None: + def verbose(self, msg: str, *args: Any, **kwargs: Any) -> None: self.log(VERBOSE, msg, *args, **kwargs) def process(self, msg: str, kwargs: Dict) -> Tuple[str, Dict]: # type: ignore diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py index 53b4d056e..2bfe16597 100644 --- a/sphinx/util/nodes.py +++ b/sphinx/util/nodes.py @@ -60,7 +60,7 @@ class NodeMatcher: # => [, , ...] """ - def __init__(self, *classes: "Type[Node]", **attrs) -> None: + def __init__(self, *classes: "Type[Node]", **attrs: Any) -> None: self.classes = classes self.attrs = attrs diff --git a/sphinx/util/osutil.py b/sphinx/util/osutil.py index d74ea20fb..d35d8a129 100644 --- a/sphinx/util/osutil.py +++ b/sphinx/util/osutil.py @@ -144,7 +144,7 @@ def make_filename_from_project(project: str) -> str: return make_filename(project_suffix_re.sub('', project)).lower() -def ustrftime(format: str, *args) -> str: +def ustrftime(format: str, *args: Any) -> str: """[DEPRECATED] strftime for unicode strings.""" warnings.warn('sphinx.util.osutil.ustrtime is deprecated for removal', RemovedInSphinx30Warning, stacklevel=2) diff --git a/sphinx/util/requests.py b/sphinx/util/requests.py index 4cc73a85f..e5ef40bac 100644 --- a/sphinx/util/requests.py +++ b/sphinx/util/requests.py @@ -11,7 +11,7 @@ import sys import warnings from contextlib import contextmanager -from typing import Generator, Union +from typing import Any, Generator, Union from urllib.parse import urlsplit import pkg_resources @@ -77,7 +77,7 @@ def is_ssl_error(exc: Exception) -> bool: @contextmanager -def ignore_insecure_warning(**kwargs) -> Generator[None, None, None]: +def ignore_insecure_warning(**kwargs: Any) -> Generator[None, None, None]: with warnings.catch_warnings(): if not kwargs.get('verify') and InsecureRequestWarning: # ignore InsecureRequestWarning if verify=False @@ -118,7 +118,7 @@ def _get_user_agent(config: Config) -> str: ]) -def get(url: str, **kwargs) -> requests.Response: +def get(url: str, **kwargs: Any) -> requests.Response: """Sends a GET request like requests.get(). This sets up User-Agent header and TLS verification automatically.""" @@ -134,7 +134,7 @@ def get(url: str, **kwargs) -> requests.Response: return requests.get(url, **kwargs) -def head(url: str, **kwargs) -> requests.Response: +def head(url: str, **kwargs: Any) -> requests.Response: """Sends a HEAD request like requests.head(). This sets up User-Agent header and TLS verification automatically.""" diff --git a/sphinx/versioning.py b/sphinx/versioning.py index f3f9245b9..884618740 100644 --- a/sphinx/versioning.py +++ b/sphinx/versioning.py @@ -155,7 +155,7 @@ class UIDTransform(SphinxTransform): """Add UIDs to doctree for versioning.""" default_priority = 880 - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: env = self.env old_doctree = None if not env.versioning_condition: diff --git a/sphinx/writers/html.py b/sphinx/writers/html.py index 50816bcf6..ad8bf7a68 100644 --- a/sphinx/writers/html.py +++ b/sphinx/writers/html.py @@ -13,8 +13,8 @@ import os import posixpath import sys import warnings +from typing import Any, Iterable, Tuple from typing import cast -from typing import Iterable, Tuple from docutils import nodes from docutils.nodes import Element, Node, Text @@ -73,7 +73,7 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator): builder = None # type: StandaloneHTMLBuilder - def __init__(self, *args) -> None: + def __init__(self, *args: Any) -> None: if isinstance(args[0], nodes.document) and isinstance(args[1], Builder): document, builder = args else: diff --git a/sphinx/writers/html5.py b/sphinx/writers/html5.py index 8eefab141..7c570d9d6 100644 --- a/sphinx/writers/html5.py +++ b/sphinx/writers/html5.py @@ -12,8 +12,8 @@ import os import posixpath import sys import warnings +from typing import Any, Iterable, Tuple from typing import cast -from typing import Iterable, Tuple from docutils import nodes from docutils.nodes import Element, Node, Text @@ -45,7 +45,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator): builder = None # type: StandaloneHTMLBuilder - def __init__(self, *args) -> None: + def __init__(self, *args: Any) -> None: if isinstance(args[0], nodes.document) and isinstance(args[1], Builder): document, builder = args else: diff --git a/sphinx/writers/manpage.py b/sphinx/writers/manpage.py index c9ae41609..cf507f0c5 100644 --- a/sphinx/writers/manpage.py +++ b/sphinx/writers/manpage.py @@ -60,7 +60,7 @@ class NestedInlineTransform: def __init__(self, document: nodes.document) -> None: self.document = document - def apply(self, **kwargs) -> None: + def apply(self, **kwargs: Any) -> None: matcher = NodeMatcher(nodes.literal, nodes.emphasis, nodes.strong) for node in self.document.traverse(matcher): # type: TextElement if any(matcher(subnode) for subnode in node): @@ -81,7 +81,7 @@ class ManualPageTranslator(SphinxTranslator, BaseTranslator): _docinfo = {} # type: Dict[str, Any] - def __init__(self, *args) -> None: + def __init__(self, *args: Any) -> None: if isinstance(args[0], nodes.document) and isinstance(args[1], Builder): document, builder = args else: diff --git a/sphinx/writers/text.py b/sphinx/writers/text.py index a71aefa80..b5246cab8 100644 --- a/sphinx/writers/text.py +++ b/sphinx/writers/text.py @@ -13,7 +13,7 @@ import re import textwrap import warnings from itertools import groupby, chain -from typing import Callable, Dict, List, Iterable, Optional, Set, Tuple, Union +from typing import Any, Callable, Dict, List, Iterable, Optional, Set, Tuple, Union from typing import cast from docutils import nodes, writers @@ -362,7 +362,7 @@ MAXWIDTH = 70 STDINDENT = 3 -def my_wrap(text: str, width: int = MAXWIDTH, **kwargs) -> List[str]: +def my_wrap(text: str, width: int = MAXWIDTH, **kwargs: Any) -> List[str]: w = TextWrapper(width=width, **kwargs) return w.wrap(text) @@ -1182,6 +1182,6 @@ class TextTranslator(SphinxTranslator): warnings.warn('TextTranslator._make_depart_admonition() is deprecated.', RemovedInSphinx30Warning) - def depart_admonition(self, node: Element) -> None: + def depart_admonition(self: "TextTranslator", node: Element) -> None: self.end_state(first=admonitionlabels[name] + ': ') return depart_admonition diff --git a/sphinx/writers/xml.py b/sphinx/writers/xml.py index 64da854e5..c75f64e25 100644 --- a/sphinx/writers/xml.py +++ b/sphinx/writers/xml.py @@ -8,6 +8,8 @@ :license: BSD, see LICENSE for details. """ +from typing import Any + from docutils.writers.docutils_xml import Writer as BaseXMLWriter from sphinx.builders import Builder @@ -19,7 +21,7 @@ class XMLWriter(BaseXMLWriter): self.builder = builder self.translator_class = self.builder.get_translator_class() - def translate(self, *args, **kwargs) -> None: + def translate(self, *args: Any, **kwargs: Any) -> None: self.document.settings.newlines = \ self.document.settings.indents = \ self.builder.env.config.xml_pretty