From bc081e44f8b438fa1e02b17bf6c4f4ea9c91126c Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Sat, 8 Dec 2018 15:58:57 +0900 Subject: [PATCH] Fix annotations --- sphinx/directives/other.py | 3 ++- sphinx/environment/adapters/toctree.py | 6 ++--- sphinx/ext/autosummary/__init__.py | 2 +- sphinx/ext/graphviz.py | 6 +---- sphinx/ext/imgmath.py | 2 +- sphinx/ext/napoleon/docstring.py | 5 ++--- sphinx/registry.py | 3 ++- sphinx/transforms/__init__.py | 2 +- sphinx/transforms/i18n.py | 22 ++++++++++--------- sphinx/transforms/post_transforms/__init__.py | 4 +++- sphinx/writers/latex.py | 2 +- sphinx/writers/texinfo.py | 2 +- 12 files changed, 30 insertions(+), 29 deletions(-) diff --git a/sphinx/directives/other.py b/sphinx/directives/other.py index cc76275b9..f5c0cccda 100644 --- a/sphinx/directives/other.py +++ b/sphinx/directives/other.py @@ -8,6 +8,7 @@ """ import re +from typing import cast from docutils import nodes from docutils.parsers.rst import directives @@ -365,7 +366,7 @@ class Only(SphinxDirective): # Use these depths to determine where the nested sections should # be placed in the doctree. n_sects_to_raise = current_depth - nested_depth + 1 - parent = self.state.parent + parent = cast(nodes.Element, self.state.parent) for i in range(n_sects_to_raise): if parent.parent: parent = parent.parent diff --git a/sphinx/environment/adapters/toctree.py b/sphinx/environment/adapters/toctree.py index d217760aa..6ae720eb6 100644 --- a/sphinx/environment/adapters/toctree.py +++ b/sphinx/environment/adapters/toctree.py @@ -105,7 +105,7 @@ class TocTree: if not subnode['anchorname']: # give the whole branch a 'current' class # (useful for styling it differently) - branchnode = subnode + branchnode = subnode # type: nodes.Element while branchnode: branchnode['classes'].append('current') branchnode = branchnode.parent @@ -272,7 +272,7 @@ class TocTree: return ancestors def _toctree_prune(self, node, depth, maxdepth, collapse=False): - # type: (nodes.Node, int, int, bool) -> None + # type: (nodes.Element, int, int, bool) -> None """Utility: Cut a TOC at a specified depth.""" for subnode in node.children[:]: if isinstance(subnode, (addnodes.compact_paragraph, @@ -313,7 +313,7 @@ class TocTree: # type: (unicode, Builder, bool, Any) -> nodes.Node """Return the global TOC nodetree.""" doctree = self.env.get_doctree(self.env.config.master_doc) - toctrees = [] + toctrees = [] # type: List[addnodes.toctree] if 'includehidden' not in kwds: kwds['includehidden'] = True if 'maxdepth' not in kwds: diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py index c7ab726ca..e47c2e1f0 100644 --- a/sphinx/ext/autosummary/__init__.py +++ b/sphinx/ext/autosummary/__init__.py @@ -644,7 +644,7 @@ def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]): def get_rst_suffix(app): # type: (Sphinx) -> unicode def get_supported_format(suffix): - # type: (unicode) -> Tuple[unicode] + # type: (unicode) -> Tuple[unicode, ...] parser_class = app.registry.get_source_parsers().get(suffix) if parser_class is None: return ('restructuredtext',) diff --git a/sphinx/ext/graphviz.py b/sphinx/ext/graphviz.py index c56c7cebd..3c0cbed68 100644 --- a/sphinx/ext/graphviz.py +++ b/sphinx/ext/graphviz.py @@ -237,10 +237,6 @@ def render_dot(self, code, options, format, prefix='graphviz'): ensuredir(path.dirname(outfn)) - # graphviz expects UTF-8 by default - if isinstance(code, text_type): - code = code.encode('utf-8') - dot_args = [graphviz_dot] dot_args.extend(self.builder.config.graphviz_dot_args) dot_args.extend(['-T' + format, '-o' + outfn]) @@ -264,7 +260,7 @@ def render_dot(self, code, options, format, prefix='graphviz'): try: # Graphviz may close standard input when an error occurs, # resulting in a broken pipe on communicate() - stdout, stderr = p.communicate(code) + stdout, stderr = p.communicate(code.encode('utf-8')) except (OSError, IOError) as err: if err.errno not in (EPIPE, EINVAL): raise diff --git a/sphinx/ext/imgmath.py b/sphinx/ext/imgmath.py index 4ed831b64..31524bb84 100644 --- a/sphinx/ext/imgmath.py +++ b/sphinx/ext/imgmath.py @@ -154,7 +154,7 @@ def compile_math(latex, builder): def convert_dvi_to_image(command, name): - # type: (List[unicode], unicode) -> Tuple[unicode, unicode] + # type: (List[unicode], unicode) -> Tuple[bytes, bytes] """Convert DVI file to specific image format.""" try: p = Popen(command, stdout=PIPE, stderr=PIPE) diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py index 6a4778b52..c39939b16 100644 --- a/sphinx/ext/napoleon/docstring.py +++ b/sphinx/ext/napoleon/docstring.py @@ -13,7 +13,6 @@ import inspect import re -from collections.abc import Callable from functools import partial from sphinx.ext.napoleon.iterators import modify_iter @@ -22,7 +21,7 @@ from sphinx.util.pycompat import UnicodeMixin if False: # For type annotation - from typing import Any, Dict, List, Tuple, Type, Union # NOQA + from typing import Any, Callable, Dict, List, Tuple, Type, Union # NOQA from sphinx.application import Sphinx # NOQA from sphinx.config import Config as SphinxConfig # NOQA from sphinx.util.typing import unicode # NOQA @@ -122,7 +121,7 @@ class GoogleDocstring(UnicodeMixin): what = 'class' elif inspect.ismodule(obj): what = 'module' - elif isinstance(obj, Callable): + elif callable(obj): what = 'function' else: what = 'object' diff --git a/sphinx/registry.py b/sphinx/registry.py index c2085d03d..1bc95e9b0 100644 --- a/sphinx/registry.py +++ b/sphinx/registry.py @@ -43,6 +43,7 @@ if False: from sphinx.domains import Domain, Index # NOQA from sphinx.environment import BuildEnvironment # NOQA from sphinx.ext.autodoc import Documenter # NOQA + from sphinx.io import SphinxFileInput # NOQA from sphinx.util.typing import RoleFunction, TitleGetter, unicode # NOQA logger = logging.getLogger(__name__) @@ -337,7 +338,7 @@ class SphinxComponentRegistry: return parser def add_source_input(self, input_class, override=False): - # type: (Type[Input], bool) -> None + # type: (Type[SphinxFileInput], bool) -> None for filetype in input_class.supported: if filetype in self.source_inputs and not override: raise ExtensionError(__('source_input for %r is already registered') % diff --git a/sphinx/transforms/__init__.py b/sphinx/transforms/__init__.py index acbd38226..387dd70bd 100644 --- a/sphinx/transforms/__init__.py +++ b/sphinx/transforms/__init__.py @@ -383,7 +383,7 @@ class SphinxSmartQuotes(SmartQuotes, SphinxTransform): @property def smartquotes_action(self): - # type: () -> unicode + # type: () -> str """A smartquotes_action setting for SmartQuotes. Users can change this setting through :confval:`smartquotes_action`. diff --git a/sphinx/transforms/i18n.py b/sphinx/transforms/i18n.py index ff5ecaade..98263dbc0 100644 --- a/sphinx/transforms/i18n.py +++ b/sphinx/transforms/i18n.py @@ -30,7 +30,7 @@ from sphinx.util.pycompat import indent if False: # For type annotation - from typing import Dict, List, Tuple # NOQA + from typing import Dict, List, Tuple, Type # NOQA from sphinx.application import Sphinx # NOQA from sphinx.config import Config # NOQA from sphinx.util.typing import unicode # NOQA @@ -265,15 +265,17 @@ class Locale(SphinxTransform): patch = patch.next_node() # ignore unexpected markups in translation message - if not isinstance(patch, ( - (nodes.paragraph, # expected form of translation - nodes.title, # generated by above "Subelements phase2" - ) + - # following types are expected if - # config.gettext_additional_targets is configured - LITERAL_TYPE_NODES + - IMAGE_TYPE_NODES - )): + unexpected = ( + nodes.paragraph, # expected form of translation + nodes.title # generated by above "Subelements phase2" + ) # type: Tuple[Type[nodes.Element], ...] + + # following types are expected if + # config.gettext_additional_targets is configured + unexpected += LITERAL_TYPE_NODES + unexpected += IMAGE_TYPE_NODES + + if not isinstance(patch, unexpected): continue # skip # auto-numbered foot note reference should use original 'ids'. diff --git a/sphinx/transforms/post_transforms/__init__.py b/sphinx/transforms/post_transforms/__init__.py index 2e6f8b1ba..de1aa52ba 100644 --- a/sphinx/transforms/post_transforms/__init__.py +++ b/sphinx/transforms/post_transforms/__init__.py @@ -9,6 +9,8 @@ :license: BSD, see LICENSE for details. """ +from typing import cast + from docutils import nodes from sphinx import addnodes @@ -39,7 +41,7 @@ class ReferencesResolver(SphinxTransform): def apply(self, **kwargs): # type: (Any) -> None for node in self.document.traverse(addnodes.pending_xref): - contnode = node[0].deepcopy() + contnode = cast(nodes.TextElement, node[0].deepcopy()) newnode = None typ = node['reftype'] diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py index 0134360c4..f0ce485d7 100644 --- a/sphinx/writers/latex.py +++ b/sphinx/writers/latex.py @@ -1756,7 +1756,7 @@ class LaTeXTranslator(SphinxTranslator): length = None if 'width' in node: length = self.latex_image_length(node['width']) - elif 'width' in node[0]: + elif isinstance(node[0], nodes.image) and 'width' in node[0]: length = self.latex_image_length(node[0]['width']) self.body.append('\\begin{wrapfigure}{%s}{%s}\n\\centering' % (node['align'] == 'right' and 'r' or 'l', length or '0pt')) diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py index 6fa676b0f..c15050574 100644 --- a/sphinx/writers/texinfo.py +++ b/sphinx/writers/texinfo.py @@ -300,7 +300,7 @@ class TexinfoTranslator(SphinxTranslator): for name, content in self.indices] # each section is also a node for section in self.document.traverse(nodes.section): - title = section.next_node(nodes.Titular) + title = cast(nodes.TextElement, section.next_node(nodes.Titular)) name = (title and title.astext()) or '' section['node_name'] = add_node_name(name)