Merge pull request #5591 from tk0miya/fix_typehints

Fix type annotations
This commit is contained in:
Takeshi KOMIYA 2018-11-06 23:34:17 +09:00 committed by GitHub
commit c307787dc8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 42 additions and 42 deletions

View File

@ -775,7 +775,7 @@ class Sphinx:
def add_object_type(self, directivename, rolename, indextemplate='', def add_object_type(self, directivename, rolename, indextemplate='',
parse_node=None, ref_nodeclass=None, objname='', parse_node=None, ref_nodeclass=None, objname='',
doc_field_types=[], override=False): doc_field_types=[], override=False):
# type: (unicode, unicode, unicode, Callable, nodes.Node, unicode, List, bool) -> None # type: (unicode, unicode, unicode, Callable, Type[nodes.Node], unicode, List, bool) -> None # NOQA
"""Register a new object type. """Register a new object type.
This method is a very convenient way to add a new :term:`object` type This method is a very convenient way to add a new :term:`object` type

View File

@ -41,7 +41,7 @@ except ImportError:
if False: if False:
# For type annotation # For type annotation
from typing import Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple, Union # NOQA from typing import Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple, Type, Union # NOQA
from sphinx.application import Sphinx # NOQA from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA from sphinx.config import Config # NOQA
from sphinx.environment import BuildEnvironment # NOQA from sphinx.environment import BuildEnvironment # NOQA
@ -121,7 +121,7 @@ class Builder:
self.versioning_compare) self.versioning_compare)
def get_translator_class(self, *args): def get_translator_class(self, *args):
# type: (Any) -> nodes.NodeVisitor # type: (Any) -> Type[nodes.NodeVisitor]
"""Return a class of translator.""" """Return a class of translator."""
return self.app.registry.get_translator_class(self) return self.app.registry.get_translator_class(self)

View File

@ -165,7 +165,7 @@ class Author(SphinxDirective):
# type: () -> List[nodes.Node] # type: () -> List[nodes.Node]
if not self.config.show_authors: if not self.config.show_authors:
return [] return []
para = nodes.paragraph(translatable=False) para = nodes.paragraph(translatable=False) # type: nodes.Node
emph = nodes.emphasis() emph = nodes.emphasis()
para += emph para += emph
if self.name == 'sectionauthor': if self.name == 'sectionauthor':
@ -247,7 +247,7 @@ class Centered(SphinxDirective):
# type: () -> List[nodes.Node] # type: () -> List[nodes.Node]
if not self.arguments: if not self.arguments:
return [] return []
subnode = addnodes.centered() subnode = addnodes.centered() # type: nodes.Node
inodes, messages = self.state.inline_text(self.arguments[0], inodes, messages = self.state.inline_text(self.arguments[0],
self.lineno) self.lineno)
subnode.extend(inodes) subnode.extend(inodes)

View File

@ -17,7 +17,7 @@ from sphinx.locale import _
if False: if False:
# For type annotation # For type annotation
from typing import Any, Callable, Dict, Iterable, List, Tuple, Type, Union # NOQA from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union # NOQA
from docutils import nodes # NOQA from docutils import nodes # NOQA
from docutils.parsers.rst.states import Inliner # NOQA from docutils.parsers.rst.states import Inliner # NOQA
from sphinx.builders import Builder # NOQA from sphinx.builders import Builder # NOQA
@ -149,7 +149,7 @@ class Domain:
#: role name -> a warning message if reference is missing #: role name -> a warning message if reference is missing
dangling_warnings = {} # type: Dict[unicode, unicode] dangling_warnings = {} # type: Dict[unicode, unicode]
#: node_class -> (enum_node_type, title_getter) #: node_class -> (enum_node_type, title_getter)
enumerable_nodes = {} # type: Dict[nodes.Node, Tuple[unicode, Callable]] enumerable_nodes = {} # type: Dict[Type[nodes.Node], Tuple[unicode, Callable]]
#: data value for a fresh environment #: data value for a fresh environment
initial_data = {} # type: Dict initial_data = {} # type: Dict
@ -201,7 +201,7 @@ class Domain:
self._role2type.setdefault(role, []).append(name) self._role2type.setdefault(role, []).append(name)
def role(self, name): def role(self, name):
# type: (unicode) -> Callable # type: (unicode) -> RoleFunction
"""Return a role adapter function that always gives the registered """Return a role adapter function that always gives the registered
role its full name ('domain:name') as the first argument. role its full name ('domain:name') as the first argument.
""" """
@ -212,7 +212,7 @@ class Domain:
fullname = '%s:%s' % (self.name, name) fullname = '%s:%s' % (self.name, name)
def role_adapter(typ, rawtext, text, lineno, inliner, options={}, content=[]): def role_adapter(typ, rawtext, text, lineno, inliner, options={}, content=[]):
# type: (unicode, unicode, unicode, int, Inliner, Dict, List[unicode]) -> nodes.Node # NOQA # type: (unicode, unicode, unicode, int, Inliner, Optional[Dict], Optional[List[unicode]]) -> Tuple[List[nodes.Node], List[nodes.Node]] # NOQA
return self.roles[name](fullname, rawtext, text, lineno, return self.roles[name](fullname, rawtext, text, lineno,
inliner, options, content) inliner, options, content)
self._role_cache[name] = role_adapter self._role_cache[name] = role_adapter

View File

@ -63,7 +63,7 @@ class VersionChange(SphinxDirective):
def run(self): def run(self):
# type: () -> List[nodes.Node] # type: () -> List[nodes.Node]
node = addnodes.versionmodified() node = addnodes.versionmodified() # type: nodes.Node
node.document = self.state.document node.document = self.state.document
set_source_info(self, node) set_source_info(self, node)
node['type'] = self.name node['type'] = self.name

View File

@ -21,11 +21,10 @@ from sphinx.util.nodes import make_refnode
if False: if False:
# For type annotation # For type annotation
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union # NOQA from typing import Any, Callable, Dict, Iterable, List, Tuple, Type, Union # NOQA
from sphinx.application import Sphinx # NOQA from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA from sphinx.builders import Builder # NOQA
from sphinx.environment import BuildEnvironment # NOQA from sphinx.environment import BuildEnvironment # NOQA
from sphinx.util.typing import RoleFunction # NOQA
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -52,7 +51,7 @@ class MathDomain(Domain):
enumerable_nodes = { # node_class -> (figtype, title_getter) enumerable_nodes = { # node_class -> (figtype, title_getter)
displaymath: ('displaymath', None), displaymath: ('displaymath', None),
nodes.math_block: ('displaymath', None), nodes.math_block: ('displaymath', None),
} # type: Dict[nodes.Node, Tuple[unicode, Callable]] } # type: Dict[Type[nodes.Node], Tuple[unicode, Callable]]
roles = { roles = {
'numref': MathReferenceRole(), 'numref': MathReferenceRole(),
} }

View File

@ -16,7 +16,7 @@ from copy import copy
from docutils import nodes from docutils import nodes
from docutils.parsers.rst import directives from docutils.parsers.rst import directives
from docutils.statemachine import ViewList from docutils.statemachine import StringList
from sphinx import addnodes from sphinx import addnodes
from sphinx.deprecation import RemovedInSphinx30Warning from sphinx.deprecation import RemovedInSphinx30Warning
@ -127,7 +127,7 @@ class Target(SphinxDirective):
targetname = '%s-%s' % (self.name, fullname) targetname = '%s-%s' % (self.name, fullname)
node = nodes.target('', '', ids=[targetname]) node = nodes.target('', '', ids=[targetname])
self.state.document.note_explicit_target(node) self.state.document.note_explicit_target(node)
ret = [node] ret = [node] # type: List[nodes.Node]
if self.indextemplate: if self.indextemplate:
indexentry = self.indextemplate % (fullname,) indexentry = self.indextemplate % (fullname,)
indextype = 'single' indextype = 'single'
@ -294,7 +294,7 @@ class Glossary(SphinxDirective):
# be* a definition list. # be* a definition list.
# first, collect single entries # first, collect single entries
entries = [] # type: List[Tuple[List[Tuple[unicode, unicode, int]], ViewList]] entries = [] # type: List[Tuple[List[Tuple[unicode, unicode, int]], StringList]]
in_definition = True in_definition = True
was_empty = True was_empty = True
messages = [] messages = []
@ -316,7 +316,7 @@ class Glossary(SphinxDirective):
messages.append(self.state.reporter.system_message( messages.append(self.state.reporter.system_message(
2, 'glossary term must be preceded by empty line', 2, 'glossary term must be preceded by empty line',
source=source, line=lineno)) source=source, line=lineno))
entries.append(([(line, source, lineno)], ViewList())) entries.append(([(line, source, lineno)], StringList()))
in_definition = False in_definition = False
# second term and following # second term and following
else: else:
@ -346,9 +346,9 @@ class Glossary(SphinxDirective):
# now, parse all the entries into a big definition list # now, parse all the entries into a big definition list
items = [] items = []
for terms, definition in entries: for terms, definition in entries:
termtexts = [] termtexts = [] # type: List[unicode]
termnodes = [] termnodes = [] # type: List[nodes.Node]
system_messages = [] # type: List[unicode] system_messages = [] # type: List[nodes.Node]
for line, source, lineno in terms: for line, source, lineno in terms:
parts = split_term_classifiers(line) parts = split_term_classifiers(line)
# parse the term with inline markup # parse the term with inline markup
@ -385,7 +385,7 @@ class Glossary(SphinxDirective):
def token_xrefs(text): def token_xrefs(text):
# type: (unicode) -> List[nodes.Node] # type: (unicode) -> List[nodes.Node]
retnodes = [] retnodes = [] # type: List[nodes.Node]
pos = 0 pos = 0
for m in token_re.finditer(text): for m in token_re.finditer(text):
if m.start() > pos: if m.start() > pos:
@ -415,7 +415,7 @@ class ProductionList(SphinxDirective):
def run(self): def run(self):
# type: () -> List[nodes.Node] # type: () -> List[nodes.Node]
objects = self.env.domaindata['std']['objects'] objects = self.env.domaindata['std']['objects']
node = addnodes.productionlist() node = addnodes.productionlist() # type: nodes.Node
messages = [] # type: List[nodes.Node] messages = [] # type: List[nodes.Node]
i = 0 i = 0
@ -520,7 +520,7 @@ class StandardDomain(Domain):
nodes.figure: ('figure', None), nodes.figure: ('figure', None),
nodes.table: ('table', None), nodes.table: ('table', None),
nodes.container: ('code-block', None), nodes.container: ('code-block', None),
} # type: Dict[nodes.Node, Tuple[unicode, Callable]] } # type: Dict[Type[nodes.Node], Tuple[unicode, Callable]]
def __init__(self, env): def __init__(self, env):
# type: (BuildEnvironment) -> None # type: (BuildEnvironment) -> None

View File

@ -120,7 +120,7 @@ class TocTree:
# type: (addnodes.toctree, List[nodes.Node], bool, bool) -> List[nodes.Node] # type: (addnodes.toctree, List[nodes.Node], bool, bool) -> List[nodes.Node]
"""Return TOC entries for a toctree node.""" """Return TOC entries for a toctree node."""
refs = [(e[0], e[1]) for e in toctreenode['entries']] refs = [(e[0], e[1]) for e in toctreenode['entries']]
entries = [] entries = [] # type: List[nodes.Node]
for (title, ref) in refs: for (title, ref) in refs:
try: try:
refdoc = None refdoc = None
@ -293,7 +293,7 @@ class TocTree:
self._toctree_prune(subnode, depth + 1, maxdepth, collapse) self._toctree_prune(subnode, depth + 1, maxdepth, collapse)
def get_toc_for(self, docname, builder): def get_toc_for(self, docname, builder):
# type: (unicode, Builder) -> Dict[unicode, nodes.Node] # type: (unicode, Builder) -> nodes.Node
"""Return a TOC nodetree -- for use on the same page only!""" """Return a TOC nodetree -- for use on the same page only!"""
tocdepth = self.env.metadata[docname].get('tocdepth', 0) tocdepth = self.env.metadata[docname].get('tocdepth', 0)
try: try:

View File

@ -370,7 +370,7 @@ class InheritanceDiagram(SphinxDirective):
# references to real URLs later. These nodes will eventually be # references to real URLs later. These nodes will eventually be
# removed from the doctree after we're done with them. # removed from the doctree after we're done with them.
for name in graph.get_all_class_names(): for name in graph.get_all_class_names():
refnodes, x = class_role( refnodes, x = class_role( # type: ignore
'class', ':class:`%s`' % name, name, 0, self.state) 'class', ':class:`%s`' % name, name, 0, self.state)
node.extend(refnodes) node.extend(refnodes)
# Store the graph object so we can use it to generate the # Store the graph object so we can use it to generate the

View File

@ -22,6 +22,7 @@ if False:
from typing import Any, Dict # NOQA from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA from sphinx.environment import BuildEnvironment # NOQA
from sphinx.writers.html import HTMLTranslator # NOQA
def html_visit_math(self, node): def html_visit_math(self, node):
@ -32,7 +33,7 @@ def html_visit_math(self, node):
def html_visit_displaymath(self, node): def html_visit_displaymath(self, node):
# type: (nodes.NodeVisitor, nodes.Node) -> None # type: (HTMLTranslator, nodes.Node) -> None
if node['nowrap']: if node['nowrap']:
self.body.append(self.starttag(node, 'div', CLASS='math notranslate nohighlight')) self.body.append(self.starttag(node, 'div', CLASS='math notranslate nohighlight'))
self.body.append(self.encode(node.astext())) self.body.append(self.encode(node.astext()))

View File

@ -25,6 +25,7 @@ if False:
from typing import Any, Dict # NOQA from typing import Any, Dict # NOQA
from sphinx.application import Sphinx # NOQA from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA from sphinx.environment import BuildEnvironment # NOQA
from sphinx.writers.html import HTMLTranslator # NOQA
def html_visit_math(self, node): def html_visit_math(self, node):
@ -37,7 +38,7 @@ def html_visit_math(self, node):
def html_visit_displaymath(self, node): def html_visit_displaymath(self, node):
# type: (nodes.NodeVisitor, nodes.Node) -> None # type: (HTMLTranslator, nodes.Node) -> None
self.body.append(self.starttag(node, 'div', CLASS='math notranslate nohighlight')) self.body.append(self.starttag(node, 'div', CLASS='math notranslate nohighlight'))
if node['nowrap']: if node['nowrap']:
self.body.append(self.encode(node.astext())) self.body.append(self.encode(node.astext()))

View File

@ -41,7 +41,7 @@ from sphinx.versioning import UIDTransform
if False: if False:
# For type annotation # For type annotation
from typing import Any, Dict, List, Tuple, Union # NOQA from typing import Any, Dict, List, Tuple, Type, Union # NOQA
from docutils import nodes # NOQA from docutils import nodes # NOQA
from docutils.io import Input # NOQA from docutils.io import Input # NOQA
from docutils.parsers import Parser # NOQA from docutils.parsers import Parser # NOQA
@ -69,7 +69,7 @@ class SphinxBaseReader(standalone.Reader):
standalone.Reader.__init__(self, *args, **kwargs) standalone.Reader.__init__(self, *args, **kwargs)
def get_transforms(self): def get_transforms(self):
# type: () -> List[Transform] # type: () -> List[Type[Transform]]
return standalone.Reader.get_transforms(self) + self.transforms return standalone.Reader.get_transforms(self) + self.transforms
def new_document(self): def new_document(self):
@ -101,7 +101,7 @@ class SphinxStandaloneReader(SphinxBaseReader):
UnreferencedFootnotesDetector, SphinxSmartQuotes, ManpageLink, UnreferencedFootnotesDetector, SphinxSmartQuotes, ManpageLink,
SphinxDomains, SubstitutionDefinitionsRemover, DoctreeReadEvent, SphinxDomains, SubstitutionDefinitionsRemover, DoctreeReadEvent,
UIDTransform, UIDTransform,
] # type: List[Transform] ] # type: List[Type[Transform]]
def __init__(self, app, *args, **kwargs): def __init__(self, app, *args, **kwargs):
# type: (Sphinx, Any, Any) -> None # type: (Sphinx, Any, Any) -> None
@ -123,7 +123,7 @@ class SphinxI18nReader(SphinxBaseReader):
AutoNumbering, SortIds, RemoveTranslatableInline, AutoNumbering, SortIds, RemoveTranslatableInline,
FilterSystemMessages, RefOnlyBulletListTransform, FilterSystemMessages, RefOnlyBulletListTransform,
UnreferencedFootnotesDetector, SphinxSmartQuotes, ManpageLink, UnreferencedFootnotesDetector, SphinxSmartQuotes, ManpageLink,
SubstitutionDefinitionsRemover] SubstitutionDefinitionsRemover] # type: List[Type[Transform]]
def set_lineno_for_reporter(self, lineno): def set_lineno_for_reporter(self, lineno):
# type: (int) -> None # type: (int) -> None

View File

@ -116,7 +116,7 @@ class SphinxComponentRegistry:
self.source_suffix = {} # type: Dict[unicode, unicode] self.source_suffix = {} # type: Dict[unicode, unicode]
#: custom translators; builder name -> translator class #: custom translators; builder name -> translator class
self.translators = {} # type: Dict[unicode, nodes.NodeVisitor] self.translators = {} # type: Dict[unicode, Type[nodes.NodeVisitor]]
#: custom handlers for translators #: custom handlers for translators
#: a dict of builder name -> dict of node name -> visitor and departure functions #: a dict of builder name -> dict of node name -> visitor and departure functions
@ -231,7 +231,7 @@ class SphinxComponentRegistry:
def add_object_type(self, directivename, rolename, indextemplate='', def add_object_type(self, directivename, rolename, indextemplate='',
parse_node=None, ref_nodeclass=None, objname='', parse_node=None, ref_nodeclass=None, objname='',
doc_field_types=[], override=False): doc_field_types=[], override=False):
# type: (unicode, unicode, unicode, Callable, nodes.Node, unicode, List, bool) -> None # type: (unicode, unicode, unicode, Callable, Type[nodes.Node], unicode, List, bool) -> None # NOQA
logger.debug('[app] adding object type: %r', logger.debug('[app] adding object type: %r',
(directivename, rolename, indextemplate, parse_node, (directivename, rolename, indextemplate, parse_node,
ref_nodeclass, objname, doc_field_types)) ref_nodeclass, objname, doc_field_types))

View File

@ -13,11 +13,11 @@
if False: if False:
# For type annotation # For type annotation
from docutils import nodes # NOQA from docutils import nodes # NOQA
from docutils.writers.html4css1 import Writer # NOQA from sphinx.builders.html import HTMLTranslator # NOQA
def get_node_equation_number(writer, node): def get_node_equation_number(writer, node):
# type: (Writer, nodes.Node) -> unicode # type: (HTMLTranslator, nodes.Node) -> unicode
if writer.builder.config.math_numfig and writer.builder.config.numfig: if writer.builder.config.math_numfig and writer.builder.config.numfig:
figtype = 'displaymath' figtype = 'displaymath'
if writer.builder.name == 'singlehtml': if writer.builder.name == 'singlehtml':
@ -27,11 +27,9 @@ def get_node_equation_number(writer, node):
id = node['ids'][0] id = node['ids'][0]
number = writer.builder.fignumbers.get(key, {}).get(id, ()) number = writer.builder.fignumbers.get(key, {}).get(id, ())
number = '.'.join(map(str, number)) return '.'.join(map(str, number))
else: else:
number = node['number'] return node['number']
return number
def wrap_displaymath(text, label, numbering): def wrap_displaymath(text, label, numbering):

View File

@ -9,7 +9,7 @@
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from typing import Callable, Dict, List, Tuple from typing import Callable, Dict, List, Optional, Tuple
from docutils import nodes from docutils import nodes
from docutils.parsers.rst.states import Inliner from docutils.parsers.rst.states import Inliner
@ -17,7 +17,8 @@ from six import text_type
# common role functions # common role functions
RoleFunction = Callable[[text_type, text_type, text_type, int, Inliner, Dict, List[text_type]], RoleFunction = Callable[[text_type, text_type, text_type, int, Inliner,
Optional[Dict], Optional[List[text_type]]],
Tuple[List[nodes.Node], List[nodes.Node]]] Tuple[List[nodes.Node], List[nodes.Node]]]
# title getter functions for enumerable nodes (see sphinx.domains.std) # title getter functions for enumerable nodes (see sphinx.domains.std)