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: if False:
# For type annotation # 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 import nodes # NOQA
from docutils.parsers import Parser # NOQA from docutils.parsers import Parser # NOQA
from docutils.transforms import Transform # NOQA from docutils.transforms import Transform # NOQA

View File

@ -11,7 +11,7 @@
import pickle import pickle
import time import time
from os import path 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 import nodes
from docutils.nodes import Node from docutils.nodes import Node
@ -44,6 +44,7 @@ except ImportError:
if False: if False:
# For type annotation # For type annotation
from typing import Type # for python3.5.1
from sphinx.application import Sphinx from sphinx.application import Sphinx
@ -117,7 +118,7 @@ class Builder:
self.env.set_versioning_method(self.versioning_method, self.env.set_versioning_method(self.versioning_method,
self.versioning_compare) 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 a class of translator."""
return self.app.registry.get_translator_class(self) 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 io import StringIO
from os import path, walk, getenv from os import path, walk, getenv
from time import time 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 uuid import uuid4
from docutils import nodes 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.osutil import relpath, ensuredir, canon_path
from sphinx.util.tags import Tags from sphinx.util.tags import Tags
if False:
# For type annotation
from typing import DefaultDict # for python3.5.1
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)

View File

@ -15,7 +15,7 @@ import sys
import warnings import warnings
from hashlib import md5 from hashlib import md5
from os import path 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 import nodes
from docutils.core import publish_parts 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.util.tags import Tags
from sphinx.writers.html import HTMLWriter, HTMLTranslator 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 # HTML5 Writer is avialable or not
if is_html5_writer_available(): if is_html5_writer_available():
from sphinx.writers.html5 import HTML5Translator from sphinx.writers.html5 import HTML5Translator
@ -331,7 +336,7 @@ class StandaloneHTMLBuilder(Builder):
self.script_files.append(JavaScript(filename, **kwargs)) self.script_files.append(JavaScript(filename, **kwargs))
@property @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: if not html5_ready or self.config.html4_writer:
return HTMLTranslator return HTMLTranslator
else: else:

View File

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

View File

@ -14,7 +14,8 @@ from importlib import import_module
if False: if False:
# For type annotation # 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): class RemovedInSphinx30Warning(DeprecationWarning):

View File

@ -10,7 +10,7 @@
""" """
import copy 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 import nodes
from docutils.nodes import Element, Node, system_message from docutils.nodes import Element, Node, system_message
@ -24,6 +24,7 @@ from sphinx.util.typing import RoleFunction
if False: if False:
# For type annotation # For type annotation
from typing import Type # for python3.5.1
from sphinx.builders import Builder from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment from sphinx.environment import BuildEnvironment

View File

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

View File

@ -12,7 +12,7 @@ import re
import unicodedata import unicodedata
import warnings import warnings
from copy import copy 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 typing import cast
from docutils import nodes from docutils import nodes
@ -35,6 +35,7 @@ from sphinx.util.typing import RoleFunction
if False: if False:
# For type annotation # For type annotation
from typing import Type # for python3.5.1
from sphinx.application import Sphinx from sphinx.application import Sphinx
from sphinx.builders import Builder from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment from sphinx.environment import BuildEnvironment
@ -910,7 +911,7 @@ class StandardDomain(Domain):
def get_enumerable_node_type(self, node: Node) -> str: def get_enumerable_node_type(self, node: Node) -> str:
"""Get type of enumerable nodes.""" """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) return any(isinstance(child, cls) for child in node)
if isinstance(node, nodes.section): if isinstance(node, nodes.section):

View File

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

View File

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

View File

@ -7,7 +7,7 @@
""" """
import warnings 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 import nodes
from docutils.nodes import Element, Node 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.docutils import SphinxDirective, switch_source_input
from sphinx.util.nodes import nested_parse_with_titles 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__) logger = logging.getLogger(__name__)
@ -70,7 +75,7 @@ class DocumenterBridge:
logger.warning(msg, location=(self.env.docname, self.lineno)) 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: ) -> Options:
"""Recognize options of Documenter from user input.""" """Recognize options of Documenter from user input."""
for name in AUTODOC_DEFAULT_OPTIONS: for name in AUTODOC_DEFAULT_OPTIONS:

View File

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

View File

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

View File

@ -16,7 +16,7 @@ import time
import warnings import warnings
from io import StringIO from io import StringIO
from os import path 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 import nodes
from docutils.nodes import Element, Node, TextElement from docutils.nodes import Element, Node, TextElement
@ -35,6 +35,7 @@ from sphinx.util.osutil import relpath
if False: if False:
# For type annotation # For type annotation
from typing import Type # for python3.5.1
from sphinx.application import Sphinx from sphinx.application import Sphinx

View File

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

View File

@ -35,7 +35,8 @@ from sphinx.versioning import UIDTransform
if False: if False:
# For type annotation # 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 import nodes # NOQA
from docutils.frontend import Values # NOQA from docutils.frontend import Values # NOQA
from docutils.io import Input # NOQA from docutils.io import Input # NOQA

View File

@ -18,7 +18,8 @@ from sphinx.util.rst import append_epilog, prepend_prolog
if False: if False:
# For type annotation # 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 import nodes # NOQA
from docutils.transforms import Transform # NOQA from docutils.transforms import Transform # NOQA
from sphinx.application import Sphinx # NOQA from sphinx.application import Sphinx # NOQA

View File

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

View File

@ -30,7 +30,8 @@ from sphinx.util.logging import prefixed_warnings
if False: if False:
# For type annotation # 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 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

View File

@ -23,7 +23,8 @@ from sphinx.util.nodes import split_explicit_title, process_index_entry, \
if False: if False:
# For type annotation # 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 docutils.parsers.rst.states import Inliner # 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

View File

@ -23,7 +23,8 @@ from sphinx.util import jsdump, rpartition
if False: if False:
# For type annotation # 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 docutils import nodes # NOQA
from sphinx.environment import BuildEnvironment # NOQA from sphinx.environment import BuildEnvironment # NOQA

View File

@ -29,7 +29,8 @@ from sphinx.util.nodes import (
if False: if False:
# For type annotation # 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.application import Sphinx # NOQA
from sphinx.config import Config # NOQA from sphinx.config import Config # NOQA

View File

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

View File

@ -10,7 +10,7 @@
""" """
import warnings import warnings
from typing import Any, Dict, List, Tuple, Type, Union from typing import Any, Dict, List, Tuple, Union
from typing import cast from typing import cast
from docutils import nodes from docutils import nodes
@ -22,6 +22,7 @@ from sphinx.util.typing import TextlikeNode
if False: if False:
# For type annotation # For type annotation
from typing import Type # for python3.5.1
from sphinx.environment import BuildEnvironment from sphinx.environment import BuildEnvironment
from sphinx.directive import ObjectDescription from sphinx.directive import ObjectDescription
@ -65,7 +66,7 @@ class Field:
self.bodyrolename = bodyrolename self.bodyrolename = bodyrolename
def make_xref(self, rolename: str, domain: str, target: str, 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: contnode: Node = None, env: "BuildEnvironment" = None) -> Node:
if not rolename: if not rolename:
return contnode or innernode(target, target) return contnode or innernode(target, target)
@ -77,7 +78,7 @@ class Field:
return refnode return refnode
def make_xrefs(self, rolename: str, domain: str, target: str, 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]: contnode: Node = None, env: "BuildEnvironment" = None) -> List[Node]:
return [self.make_xref(rolename, domain, target, innernode, contnode, env)] 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 distutils.version import LooseVersion
from os import path from os import path
from types import ModuleType 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 from typing import cast
import docutils import docutils
@ -40,6 +40,7 @@ report_re = re.compile('^(.+?:(?:\\d+)?): \\((DEBUG|INFO|WARNING|ERROR|SEVERE)/(
if False: if False:
# For type annotation # For type annotation
from typing import Type # for python3.5.1
from sphinx.builders import Builder from sphinx.builders import Builder
from sphinx.config import Config from sphinx.config import Config
from sphinx.environment import BuildEnvironment from sphinx.environment import BuildEnvironment
@ -71,7 +72,7 @@ def is_directive_registered(name: str) -> bool:
return name in directives._directives 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. """Register a directive to docutils.
This modifies global state of docutils. So it is better to use this 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) 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.""" """Check the *node* is already registered."""
return hasattr(nodes.GenericNodeVisitor, 'visit_' + node.__name__) 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. """Register a node to docutils.
This modifies global state of some visitors. So it is better to use this 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) additional_nodes.add(node)
def unregister_node(node: Type[Element]) -> None: def unregister_node(node: "Type[Element]") -> None:
"""Unregister a node from docutils. """Unregister a node from docutils.
This is inverse of ``nodes._add_nodes_class_names()``. This is inverse of ``nodes._add_nodes_class_names()``.
@ -186,7 +187,7 @@ class sphinx_domains:
def __enter__(self) -> None: def __enter__(self) -> None:
self.enable() 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() self.disable()
return False return False
@ -229,7 +230,7 @@ class sphinx_domains:
raise ElementLookupError 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: try:
return self.lookup_domain_element('directive', directive_name) return self.lookup_domain_element('directive', directive_name)
except ElementLookupError: except ElementLookupError:

View File

@ -12,7 +12,7 @@ import logging
import logging.handlers import logging.handlers
from collections import defaultdict from collections import defaultdict
from contextlib import contextmanager 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 import nodes
from docutils.nodes import Node from docutils.nodes import Node
@ -23,6 +23,7 @@ from sphinx.util.console import colorize
if False: if False:
# For type annotation # For type annotation
from typing import Type # for python3.5.1
from sphinx.application import Sphinx from sphinx.application import Sphinx

View File

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

View File

@ -19,11 +19,15 @@ import time
import warnings import warnings
from io import StringIO from io import StringIO
from os import path 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.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
from sphinx.testing.path import path as Path 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. # Errnos that we need.
EEXIST = getattr(errno, 'EEXIST', 0) # RemovedInSphinx40Warning EEXIST = getattr(errno, 'EEXIST', 0) # RemovedInSphinx40Warning
ENOENT = getattr(errno, 'ENOENT', 0) # RemovedInSphinx40Warning ENOENT = getattr(errno, 'ENOENT', 0) # RemovedInSphinx40Warning
@ -248,7 +252,7 @@ class FileAvoidWrite:
def __enter__(self) -> "FileAvoidWrite": def __enter__(self) -> "FileAvoidWrite":
return self 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() self.close()
return True return True