Merge pull request #5735 from tk0miya/fix_typehints_for_minor

Fix annotations
This commit is contained in:
Takeshi KOMIYA 2018-12-08 23:44:53 +09:00 committed by GitHub
commit 385d6a6572
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 30 additions and 29 deletions

View File

@ -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

View File

@ -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:

View File

@ -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',)

View File

@ -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

View File

@ -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)

View File

@ -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'

View File

@ -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') %

View File

@ -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`.

View File

@ -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'.

View File

@ -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']

View File

@ -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'))

View File

@ -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 '<untitled>'
section['node_name'] = add_node_name(name)