Merge pull request #6579 from tk0miya/refactor_type_annotation_py351

Fix type annotation for python 3.5.1
This commit is contained in:
Takeshi KOMIYA 2019-07-14 00:00:18 +09:00 committed by GitHub
commit 5db23ea002
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 115 additions and 56 deletions

View File

@ -48,7 +48,8 @@ from sphinx.util.tags import Tags
if False:
# For type annotation
from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Tuple, Type, Union # NOQA
from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Tuple, Union # NOQA
from typing import Type # for python3.5.1
from docutils import nodes # NOQA
from docutils.parsers import Parser # NOQA
from docutils.transforms import Transform # NOQA

View File

@ -11,7 +11,7 @@
import pickle
import time
from os import path
from typing import Any, Dict, Iterable, List, Sequence, Set, Tuple, Type, Union
from typing import Any, Dict, Iterable, List, Sequence, Set, Tuple, Union
from docutils import nodes
from docutils.nodes import Node
@ -44,6 +44,7 @@ except ImportError:
if False:
# For type annotation
from typing import Type # for python3.5.1
from sphinx.application import Sphinx
@ -117,7 +118,7 @@ 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) -> "Type[nodes.NodeVisitor]":
"""Return a class of translator."""
return self.app.registry.get_translator_class(self)

View File

@ -14,7 +14,7 @@ from datetime import datetime, tzinfo, timedelta
from io import StringIO
from os import path, walk, getenv
from time import time
from typing import Any, DefaultDict, Dict, Iterable, List, Set, Tuple, Union
from typing import Any, Dict, Iterable, List, Set, Tuple, Union
from uuid import uuid4
from docutils import nodes
@ -33,6 +33,9 @@ from sphinx.util.nodes import extract_messages, traverse_translatable_index
from sphinx.util.osutil import relpath, ensuredir, canon_path
from sphinx.util.tags import Tags
if False:
# For type annotation
from typing import DefaultDict # for python3.5.1
logger = logging.getLogger(__name__)

View File

@ -15,7 +15,7 @@ import sys
import warnings
from hashlib import md5
from os import path
from typing import Any, Dict, IO, Iterable, Iterator, List, Set, Type, Tuple
from typing import Any, Dict, IO, Iterable, Iterator, List, Set, Tuple
from docutils import nodes
from docutils.core import publish_parts
@ -48,6 +48,11 @@ from sphinx.util.osutil import os_path, relative_uri, ensuredir, movefile, copyf
from sphinx.util.tags import Tags
from sphinx.writers.html import HTMLWriter, HTMLTranslator
if False:
# For type annotation
from typing import Type # for python3.5.1
# HTML5 Writer is avialable or not
if is_html5_writer_available():
from sphinx.writers.html5 import HTML5Translator
@ -331,7 +336,7 @@ class StandaloneHTMLBuilder(Builder):
self.script_files.append(JavaScript(filename, **kwargs))
@property
def default_translator_class(self) -> Type[nodes.NodeVisitor]: # type: ignore
def default_translator_class(self) -> "Type[nodes.NodeVisitor]": # type: ignore
if not html5_ready or self.config.html4_writer:
return HTMLTranslator
else:

View File

@ -9,7 +9,7 @@
"""
from os import path
from typing import Any, Dict, Iterator, Set, Type, Union
from typing import Any, Dict, Iterator, Set, Union
from docutils import nodes
from docutils.io import StringOutput
@ -23,6 +23,11 @@ from sphinx.util import logging
from sphinx.util.osutil import ensuredir, os_path
from sphinx.writers.xml import XMLWriter, PseudoXMLWriter
if False:
# For type annotation
from typing import Type # for python3.5.1
logger = logging.getLogger(__name__)

View File

@ -14,7 +14,8 @@ from importlib import import_module
if False:
# For type annotation
from typing import Any, Dict, Type # NOQA
from typing import Any, Dict # NOQA
from typing import Type # for python3.5.1
class RemovedInSphinx30Warning(DeprecationWarning):

View File

@ -10,7 +10,7 @@
"""
import copy
from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Tuple, Type, Union
from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Tuple, Union
from docutils import nodes
from docutils.nodes import Element, Node, system_message
@ -24,6 +24,7 @@ from sphinx.util.typing import RoleFunction
if False:
# For type annotation
from typing import Type # for python3.5.1
from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment

View File

@ -10,7 +10,7 @@
import re
import warnings
from typing import Any, Dict, Iterable, Iterator, List, Tuple, Type
from typing import Any, Dict, Iterable, Iterator, List, Tuple
from typing import cast
from docutils import nodes
@ -35,6 +35,10 @@ from sphinx.util.docutils import SphinxDirective
from sphinx.util.nodes import make_refnode
from sphinx.util.typing import TextlikeNode
if False:
# For type annotation
from typing import Type # for python3.5.1
logger = logging.getLogger(__name__)
@ -119,7 +123,7 @@ def _pseudo_parse_arglist(signode: desc_signature, arglist: str) -> None:
# when it comes to handling "." and "~" prefixes.
class PyXrefMixin:
def make_xref(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = nodes.emphasis,
innernode: "Type[TextlikeNode]" = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> Node:
result = super().make_xref(rolename, domain, target, # type: ignore
innernode, contnode, env)
@ -136,7 +140,7 @@ class PyXrefMixin:
return result
def make_xrefs(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = nodes.emphasis,
innernode: "Type[TextlikeNode]" = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> List[Node]:
delims = r'(\s*[\[\]\(\),](?:\s*or\s)?\s*|\s+or\s+)'
delims_re = re.compile(delims)
@ -160,7 +164,7 @@ class PyXrefMixin:
class PyField(PyXrefMixin, Field):
def make_xref(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = nodes.emphasis,
innernode: "Type[TextlikeNode]" = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> Node:
if rolename == 'class' and target == 'None':
# None is not a type, so use obj role instead.
@ -175,7 +179,7 @@ class PyGroupedField(PyXrefMixin, GroupedField):
class PyTypedField(PyXrefMixin, TypedField):
def make_xref(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = nodes.emphasis,
innernode: "Type[TextlikeNode]" = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> Node:
if rolename == 'class' and target == 'None':
# None is not a type, so use obj role instead.

View File

@ -12,7 +12,7 @@ import re
import unicodedata
import warnings
from copy import copy
from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Type, Union
from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union
from typing import cast
from docutils import nodes
@ -35,6 +35,7 @@ from sphinx.util.typing import RoleFunction
if False:
# For type annotation
from typing import Type # for python3.5.1
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment
@ -910,7 +911,7 @@ class StandardDomain(Domain):
def get_enumerable_node_type(self, node: Node) -> str:
"""Get type of enumerable nodes."""
def has_child(node: Element, cls: Type) -> bool:
def has_child(node: Element, cls: "Type") -> bool:
return any(isinstance(child, cls) for child in node)
if isinstance(node, nodes.section):

View File

@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
from typing import Any, Dict, List, Set, Tuple, Type, TypeVar
from typing import Any, Dict, List, Set, Tuple, TypeVar
from typing import cast
from docutils import nodes
@ -23,6 +23,10 @@ from sphinx.locale import __
from sphinx.transforms import SphinxContentsFilter
from sphinx.util import url_re, logging
if False:
# For type annotation
from typing import Type # for python3.5.1
N = TypeVar('N')
@ -64,7 +68,7 @@ class TocTreeCollector(EnvironmentCollector):
docname = app.env.docname
numentries = [0] # nonlocal again...
def traverse_in_section(node: Element, cls: Type[N]) -> List[N]:
def traverse_in_section(node: Element, cls: "Type[N]") -> List[N]:
"""Like traverse(), but stay within the same section."""
result = [] # type: List[N]
if isinstance(node, cls):

View File

@ -13,7 +13,7 @@
import re
import warnings
from types import ModuleType
from typing import Any, Callable, Dict, Iterator, List, Sequence, Set, Tuple, Type, Union
from typing import Any, Callable, Dict, Iterator, List, Sequence, Set, Tuple, Union
from docutils.statemachine import StringList
@ -38,6 +38,7 @@ from sphinx.util.inspect import (
if False:
# For type annotation
from typing import Type # NOQA # for python3.5.1
from sphinx.ext.autodoc.directive import DocumenterBridge
@ -255,7 +256,7 @@ class Documenter:
self.analyzer = None # type: ModuleAnalyzer
@property
def documenters(self) -> Dict[str, Type["Documenter"]]:
def documenters(self) -> Dict[str, "Type[Documenter]"]:
"""Returns registered Documenter classes"""
return get_documenters(self.env.app)
@ -1486,7 +1487,7 @@ class SlotsAttributeDocumenter(AttributeDocumenter):
return []
def get_documenters(app: Sphinx) -> Dict[str, Type[Documenter]]:
def get_documenters(app: Sphinx) -> Dict[str, "Type[Documenter]"]:
"""Returns registered Documenter classes"""
return app.registry.documenters

View File

@ -7,7 +7,7 @@
"""
import warnings
from typing import Any, Callable, Dict, List, Set, Type
from typing import Any, Callable, Dict, List, Set
from docutils import nodes
from docutils.nodes import Element, Node
@ -23,6 +23,11 @@ from sphinx.util import logging
from sphinx.util.docutils import SphinxDirective, switch_source_input
from sphinx.util.nodes import nested_parse_with_titles
if False:
# For type annotation
from typing import Type # for python3.5.1
logger = logging.getLogger(__name__)
@ -70,7 +75,7 @@ class DocumenterBridge:
logger.warning(msg, location=(self.env.docname, self.lineno))
def process_documenter_options(documenter: Type[Documenter], config: Config, options: Dict
def process_documenter_options(documenter: "Type[Documenter]", config: Config, options: Dict
) -> Options:
"""Recognize options of Documenter from user input."""
for name in AUTODOC_DEFAULT_OPTIONS:

View File

@ -60,7 +60,7 @@ import sys
import warnings
from os import path
from types import ModuleType
from typing import Any, Dict, List, Tuple, Type
from typing import Any, Dict, List, Tuple
from typing import cast
from docutils import nodes
@ -88,6 +88,10 @@ from sphinx.util.docutils import (
from sphinx.util.matching import Matcher
from sphinx.writers.html import HTMLTranslator
if False:
# For type annotation
from typing import Type # for python3.5.1
logger = logging.getLogger(__name__)
@ -173,7 +177,7 @@ class FakeDirective(DocumenterBridge):
super().__init__({}, None, Options(), 0, state) # type: ignore
def get_documenter(app: Sphinx, obj: Any, parent: Any) -> Type[Documenter]:
def get_documenter(app: Sphinx, obj: Any, parent: Any) -> "Type[Documenter]":
"""Get an autodoc.Documenter class suitable for documenting the given
object.

View File

@ -24,7 +24,7 @@ import pydoc
import re
import sys
import warnings
from typing import Any, Callable, Dict, List, Set, Tuple, Type
from typing import Any, Callable, Dict, List, Set, Tuple
from jinja2 import BaseLoader, FileSystemLoader, TemplateNotFound
from jinja2.sandbox import SandboxedEnvironment
@ -44,6 +44,10 @@ from sphinx.util import rst
from sphinx.util.inspect import safe_getattr
from sphinx.util.osutil import ensuredir
if False:
# For type annotation
from typing import Type # for python3.5.1
logger = logging.getLogger(__name__)

View File

@ -16,7 +16,7 @@ import time
import warnings
from io import StringIO
from os import path
from typing import Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple, Type
from typing import Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple
from docutils import nodes
from docutils.nodes import Element, Node, TextElement
@ -35,6 +35,7 @@ from sphinx.util.osutil import relpath
if False:
# For type annotation
from typing import Type # for python3.5.1
from sphinx.application import Sphinx

View File

@ -13,13 +13,17 @@
import inspect
import re
from functools import partial
from typing import Any, Callable, Dict, List, Tuple, Type, Union
from typing import Any, Callable, Dict, List, Tuple, Union
from sphinx.application import Sphinx
from sphinx.config import Config as SphinxConfig
from sphinx.ext.napoleon.iterators import modify_iter
from sphinx.locale import _
if False:
# For type annotation
from typing import Type # for python3.5.1
_directive_regex = re.compile(r'\.\. \S+::')
_google_section_regex = re.compile(r'^(\s|\w)+:\s*$')
@ -735,7 +739,7 @@ class GoogleDocstring:
colon,
"".join(after_colon).strip())
def _qualify_name(self, attr_name: str, klass: Type) -> str:
def _qualify_name(self, attr_name: str, klass: "Type") -> str:
if klass and '.' not in attr_name:
if attr_name.startswith('~'):
attr_name = attr_name[1:]

View File

@ -35,7 +35,8 @@ from sphinx.versioning import UIDTransform
if False:
# For type annotation
from typing import Dict, List, Tuple, Type # NOQA
from typing import Dict, List, Tuple # NOQA
from typing import Type # for python3.5.1
from docutils import nodes # NOQA
from docutils.frontend import Values # NOQA
from docutils.io import Input # NOQA

View File

@ -18,7 +18,8 @@ from sphinx.util.rst import append_epilog, prepend_prolog
if False:
# For type annotation
from typing import Any, Dict, List, Type, Union # NOQA
from typing import Any, Dict, List, Union # NOQA
from typing import Type # for python3.5.1
from docutils import nodes # NOQA
from docutils.transforms import Transform # NOQA
from sphinx.application import Sphinx # NOQA

View File

@ -9,7 +9,6 @@
"""
import os
from typing import TYPE_CHECKING
from sphinx.locale import __
from sphinx.util import get_matching_files
@ -17,9 +16,11 @@ from sphinx.util import logging
from sphinx.util.matching import compile_matchers
from sphinx.util.osutil import SEP, relpath
if TYPE_CHECKING:
if False:
# For type annotation
from typing import Dict, List, Set # NOQA
logger = logging.getLogger(__name__)
EXCLUDE_PATHS = ['**/_sources', '.#*', '**/.#*', '*.lproj/**']

View File

@ -30,7 +30,8 @@ from sphinx.util.logging import prefixed_warnings
if False:
# For type annotation
from typing import Any, Callable, Dict, Iterator, List, Tuple, Type, Union # NOQA
from typing import Any, Callable, Dict, Iterator, List, Tuple, Union # NOQA
from typing import Type # for python3.5.1
from docutils import nodes # NOQA
from docutils.io import Input # NOQA
from docutils.parsers import Parser # NOQA

View File

@ -23,7 +23,8 @@ from sphinx.util.nodes import split_explicit_title, process_index_entry, \
if False:
# For type annotation
from typing import Any, Dict, List, Tuple, Type # NOQA
from typing import Any, Dict, List, Tuple # NOQA
from typing import Type # for python3.5.1
from docutils.parsers.rst.states import Inliner # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -23,7 +23,8 @@ from sphinx.util import jsdump, rpartition
if False:
# For type annotation
from typing import Any, Dict, IO, Iterable, List, Tuple, Type, Set # NOQA
from typing import Any, Dict, IO, Iterable, List, Tuple, Set # NOQA
from typing import Type # for python3.5.1
from docutils import nodes # NOQA
from sphinx.environment import BuildEnvironment # NOQA

View File

@ -29,7 +29,8 @@ from sphinx.util.nodes import (
if False:
# For type annotation
from typing import Dict, List, Tuple, Type # NOQA
from typing import Dict, List, Tuple # NOQA
from typing import Type # for python3.5.1
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA

View File

@ -24,9 +24,7 @@ from datetime import datetime
from hashlib import md5
from os import path
from time import mktime, strptime
from typing import (
Any, Callable, Dict, IO, Iterable, Iterator, List, Pattern, Set, Tuple, Type
)
from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Pattern, Set, Tuple
from urllib.parse import urlsplit, urlunsplit, quote_plus, parse_qsl, urlencode
from docutils.utils import relative_path
@ -53,6 +51,7 @@ from sphinx.util.matching import patfilter # noqa
if False:
# For type annotation
from typing import Type # for python3.5.1
from sphinx.application import Sphinx
from sphinx.builders import Builder
@ -655,7 +654,7 @@ class progress_message:
def __enter__(self) -> None:
logger.info(bold(self.message + '... '), nonl=True)
def __exit__(self, exc_type: Type[Exception], exc_value: Exception, traceback: Any) -> bool: # NOQA
def __exit__(self, exc_type: "Type[Exception]", exc_value: Exception, traceback: Any) -> bool: # NOQA
if isinstance(exc_value, SkipProgressMessage):
logger.info(__('skipped'))
if exc_value.args:

View File

@ -10,7 +10,7 @@
"""
import warnings
from typing import Any, Dict, List, Tuple, Type, Union
from typing import Any, Dict, List, Tuple, Union
from typing import cast
from docutils import nodes
@ -22,6 +22,7 @@ from sphinx.util.typing import TextlikeNode
if False:
# For type annotation
from typing import Type # for python3.5.1
from sphinx.environment import BuildEnvironment
from sphinx.directive import ObjectDescription
@ -65,7 +66,7 @@ class Field:
self.bodyrolename = bodyrolename
def make_xref(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = addnodes.literal_emphasis,
innernode: "Type[TextlikeNode]" = addnodes.literal_emphasis,
contnode: Node = None, env: "BuildEnvironment" = None) -> Node:
if not rolename:
return contnode or innernode(target, target)
@ -77,7 +78,7 @@ class Field:
return refnode
def make_xrefs(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = addnodes.literal_emphasis,
innernode: "Type[TextlikeNode]" = addnodes.literal_emphasis,
contnode: Node = None, env: "BuildEnvironment" = None) -> List[Node]:
return [self.make_xref(rolename, domain, target, innernode, contnode, env)]

View File

@ -17,7 +17,7 @@ from copy import copy
from distutils.version import LooseVersion
from os import path
from types import ModuleType
from typing import Any, Callable, Dict, Generator, IO, List, Optional, Set, Tuple, Type
from typing import Any, Callable, Dict, Generator, IO, List, Optional, Set, Tuple
from typing import cast
import docutils
@ -40,6 +40,7 @@ report_re = re.compile('^(.+?:(?:\\d+)?): \\((DEBUG|INFO|WARNING|ERROR|SEVERE)/(
if False:
# For type annotation
from typing import Type # for python3.5.1
from sphinx.builders import Builder
from sphinx.config import Config
from sphinx.environment import BuildEnvironment
@ -71,7 +72,7 @@ def is_directive_registered(name: str) -> bool:
return name in directives._directives
def register_directive(name: str, directive: Type[Directive]) -> None:
def register_directive(name: str, directive: "Type[Directive]") -> None:
"""Register a directive to docutils.
This modifies global state of docutils. So it is better to use this
@ -99,12 +100,12 @@ def unregister_role(name: str) -> None:
roles._roles.pop(name, None)
def is_node_registered(node: Type[Element]) -> bool:
def is_node_registered(node: "Type[Element]") -> bool:
"""Check the *node* is already registered."""
return hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__)
def register_node(node: Type[Element]) -> None:
def register_node(node: "Type[Element]") -> None:
"""Register a node to docutils.
This modifies global state of some visitors. So it is better to use this
@ -115,7 +116,7 @@ def register_node(node: Type[Element]) -> None:
additional_nodes.add(node)
def unregister_node(node: Type[Element]) -> None:
def unregister_node(node: "Type[Element]") -> None:
"""Unregister a node from docutils.
This is inverse of ``nodes._add_nodes_class_names()``.
@ -186,7 +187,7 @@ class sphinx_domains:
def __enter__(self) -> None:
self.enable()
def __exit__(self, exc_type: Type[Exception], exc_value: Exception, traceback: Any) -> bool: # NOQA
def __exit__(self, exc_type: "Type[Exception]", exc_value: Exception, traceback: Any) -> bool: # NOQA
self.disable()
return False
@ -229,7 +230,7 @@ class sphinx_domains:
raise ElementLookupError
def lookup_directive(self, directive_name: str, language_module: ModuleType, document: nodes.document) -> Tuple[Optional[Type[Directive]], List[system_message]]: # NOQA
def lookup_directive(self, directive_name: str, language_module: ModuleType, document: nodes.document) -> Tuple[Optional["Type[Directive]"], List[system_message]]: # NOQA
try:
return self.lookup_domain_element('directive', directive_name)
except ElementLookupError:

View File

@ -12,7 +12,7 @@ import logging
import logging.handlers
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, Dict, Generator, IO, List, Tuple, Type, Union
from typing import Any, Dict, Generator, IO, List, Tuple, Union
from docutils import nodes
from docutils.nodes import Node
@ -23,6 +23,7 @@ from sphinx.util.console import colorize
if False:
# For type annotation
from typing import Type # for python3.5.1
from sphinx.application import Sphinx

View File

@ -10,7 +10,7 @@
import re
import warnings
from typing import Any, Callable, Iterable, List, Set, Tuple, Type
from typing import Any, Callable, Iterable, List, Set, Tuple
from typing import cast
from docutils import nodes
@ -26,6 +26,7 @@ from sphinx.util import logging
if False:
# For type annotation
from typing import Type # for python3.5.1
from sphinx.builders import Builder
from sphinx.utils.tags import Tags
@ -59,7 +60,7 @@ class NodeMatcher:
# => [<reference ...>, <reference ...>, ...]
"""
def __init__(self, *classes: Type[Node], **attrs) -> None:
def __init__(self, *classes: "Type[Node]", **attrs) -> None:
self.classes = classes
self.attrs = attrs

View File

@ -19,11 +19,15 @@ import time
import warnings
from io import StringIO
from os import path
from typing import Any, Generator, Iterator, List, Tuple, Type
from typing import Any, Generator, Iterator, List, Tuple
from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
from sphinx.testing.path import path as Path
if False:
# For type annotation
from typing import Type # for python3.5.1
# Errnos that we need.
EEXIST = getattr(errno, 'EEXIST', 0) # RemovedInSphinx40Warning
ENOENT = getattr(errno, 'ENOENT', 0) # RemovedInSphinx40Warning
@ -248,7 +252,7 @@ class FileAvoidWrite:
def __enter__(self) -> "FileAvoidWrite":
return self
def __exit__(self, exc_type: Type[Exception], exc_value: Exception, traceback: Any) -> bool: # NOQA
def __exit__(self, exc_type: "Type[Exception]", exc_value: Exception, traceback: Any) -> bool: # NOQA
self.close()
return True