diff options
| author | Takeshi KOMIYA <i.tkomiya@gmail.com> | 2021-03-28 07:31:52 +0900 |
|---|---|---|
| committer | Takeshi KOMIYA <i.tkomiya@gmail.com> | 2021-05-03 22:41:19 +0900 |
| commit | 930bf6c327b31aec6112359695f35a2c77fbae21 (patch) | |
| tree | 77ec4b549ad46ea2c52b9ba40a0f011451378305 | |
| parent | f31af4b8158e6142d918366aa0026e40575af914 (diff) | |
| download | sphinx-git-930bf6c327b31aec6112359695f35a2c77fbae21.tar.gz | |
refactor: Add Optional to type annotations
| -rw-r--r-- | sphinx/config.py | 2 | ||||
| -rw-r--r-- | sphinx/environment/adapters/toctree.py | 4 | ||||
| -rw-r--r-- | sphinx/project.py | 4 | ||||
| -rw-r--r-- | sphinx/transforms/__init__.py | 6 | ||||
| -rw-r--r-- | sphinx/util/docfields.py | 2 | ||||
| -rw-r--r-- | sphinx/util/docutils.py | 8 | ||||
| -rw-r--r-- | sphinx/util/logging.py | 4 | ||||
| -rw-r--r-- | sphinx/util/nodes.py | 21 | ||||
| -rw-r--r-- | sphinx/util/parallel.py | 4 | ||||
| -rw-r--r-- | sphinx/util/typing.py | 2 |
10 files changed, 30 insertions, 27 deletions
diff --git a/sphinx/config.py b/sphinx/config.py index 418ecf4fb..5e265f576 100644 --- a/sphinx/config.py +++ b/sphinx/config.py @@ -309,7 +309,7 @@ class Config: self.__dict__.update(state) -def eval_config_file(filename: str, tags: Tags) -> Dict[str, Any]: +def eval_config_file(filename: str, tags: Optional[Tags]) -> Dict[str, Any]: """Evaluate a config file.""" namespace: Dict[str, Any] = {} namespace['__file__'] = filename diff --git a/sphinx/environment/adapters/toctree.py b/sphinx/environment/adapters/toctree.py index 3ee2f9ff0..6822c42c9 100644 --- a/sphinx/environment/adapters/toctree.py +++ b/sphinx/environment/adapters/toctree.py @@ -8,7 +8,7 @@ :license: BSD, see LICENSE for details. """ -from typing import TYPE_CHECKING, Any, Iterable, List, cast +from typing import TYPE_CHECKING, Any, Iterable, List, Optional, cast from docutils import nodes from docutils.nodes import Element, Node @@ -48,7 +48,7 @@ class TocTree: def resolve(self, docname: str, builder: "Builder", toctree: addnodes.toctree, prune: bool = True, maxdepth: int = 0, titles_only: bool = False, - collapse: bool = False, includehidden: bool = False) -> Element: + collapse: bool = False, includehidden: bool = False) -> Optional[Element]: """Resolve a *toctree* node into individual bullet lists with titles as items, returning None (if no containing titles are found) or a new node. diff --git a/sphinx/project.py b/sphinx/project.py index bb2314c63..d4293cdc4 100644 --- a/sphinx/project.py +++ b/sphinx/project.py @@ -10,7 +10,7 @@ import os from glob import glob -from typing import Dict, List, Set +from typing import Dict, List, Optional, Set from sphinx.locale import __ from sphinx.util import get_matching_files, logging, path_stabilize @@ -60,7 +60,7 @@ class Project: return self.docnames - def path2doc(self, filename: str) -> str: + def path2doc(self, filename: str) -> Optional[str]: """Return the docname for the filename if the file is document. *filename* should be absolute or relative to the source directory. diff --git a/sphinx/transforms/__init__.py b/sphinx/transforms/__init__.py index 213742636..66882e2b2 100644 --- a/sphinx/transforms/__init__.py +++ b/sphinx/transforms/__init__.py @@ -10,7 +10,7 @@ import re import warnings -from typing import TYPE_CHECKING, Any, Dict, Generator, List, Tuple +from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Tuple from docutils import nodes from docutils.nodes import Element, Node, Text @@ -72,8 +72,8 @@ class SphinxTransformer(Transformer): A transformer for Sphinx. """ - document: nodes.document = None - env: "BuildEnvironment" = None + document: nodes.document + env: Optional["BuildEnvironment"] = None def set_environment(self, env: "BuildEnvironment") -> None: self.env = env diff --git a/sphinx/util/docfields.py b/sphinx/util/docfields.py index f74f03265..3a3367ebe 100644 --- a/sphinx/util/docfields.py +++ b/sphinx/util/docfields.py @@ -209,7 +209,7 @@ class DocFieldTransformer: Transforms field lists in "doc field" syntax into better-looking equivalents, using the field type definitions given on a domain. """ - typemap: Dict[str, Tuple[Field, bool]] = None + typemap: Dict[str, Tuple[Field, bool]] def __init__(self, directive: "ObjectDescription") -> None: self.directive = directive diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py index 44483bdd8..c2e12e152 100644 --- a/sphinx/util/docutils.py +++ b/sphinx/util/docutils.py @@ -176,8 +176,8 @@ class sphinx_domains: """ def __init__(self, env: "BuildEnvironment") -> None: self.env = env - self.directive_func: Callable = None - self.roles_func: Callable = None + self.directive_func: Callable = lambda *args: (None, []) + self.roles_func: Callable = lambda *args: (None, []) def __enter__(self) -> None: self.enable() @@ -372,7 +372,7 @@ class SphinxRole: if name: self.name = name.lower() else: - self.name = self.env.temp_data.get('default_role') + self.name = self.env.temp_data.get('default_role', '') if not self.name: self.name = self.env.config.default_role if not self.name: @@ -491,7 +491,7 @@ class SphinxTranslator(nodes.NodeVisitor): # cache a vanilla instance of nodes.document # Used in new_document() function -__document_cache__: nodes.document = None +__document_cache__: Optional[nodes.document] = None def new_document(source_path: str, settings: Any = None) -> nodes.document: diff --git a/sphinx/util/logging.py b/sphinx/util/logging.py index 64b7d8fb4..e0f4f0e70 100644 --- a/sphinx/util/logging.py +++ b/sphinx/util/logging.py @@ -320,8 +320,8 @@ def prefixed_warnings(prefix: str) -> Generator[None, None, None]: prefix_filter.prefix = previous else: # not prefixed yet + prefix_filter = MessagePrefixFilter(prefix) try: - prefix_filter = MessagePrefixFilter(prefix) warning_handler.addFilter(prefix_filter) yield finally: @@ -472,7 +472,7 @@ class SphinxLogRecordTranslator(logging.Filter): * Make a instance of SphinxLogRecord * docname to path if location given """ - LogRecordClass: Type[logging.LogRecord] = None + LogRecordClass: Type[logging.LogRecord] def __init__(self, app: "Sphinx") -> None: self.app = app diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py index 44eb5d303..36db149b9 100644 --- a/sphinx/util/nodes.py +++ b/sphinx/util/nodes.py @@ -10,7 +10,8 @@ import re import unicodedata -from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Set, Tuple, Type, Union, cast +from typing import (TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Set, Tuple, Type, + Union, cast) from docutils import nodes from docutils.nodes import Element, Node @@ -170,7 +171,7 @@ def apply_source_workaround(node: Element) -> None: ))): logger.debug('[i18n] PATCH: %r to have source and line: %s', get_full_module_name(node), repr_domxml(node)) - node.source = get_node_source(node) + node.source = get_node_source(node) or '' node.line = 0 # need fix docutils to get `node.line` return @@ -266,7 +267,7 @@ def extract_messages(doctree: Element) -> Iterable[Tuple[Element, str]]: if node.get('translatable'): msg = '.. image:: %s' % node['uri'] else: - msg = None + msg = '' elif isinstance(node, META_TYPE_NODES): msg = node.rawcontent elif isinstance(node, nodes.pending) and is_pending_meta(node): @@ -279,14 +280,14 @@ def extract_messages(doctree: Element) -> Iterable[Tuple[Element, str]]: yield node, msg -def get_node_source(node: Element) -> str: +def get_node_source(node: Element) -> Optional[str]: for pnode in traverse_parent(node): if pnode.source: return pnode.source return None -def get_node_line(node: Element) -> int: +def get_node_line(node: Element) -> Optional[int]: for pnode in traverse_parent(node): if pnode.line: return pnode.line @@ -300,7 +301,7 @@ def traverse_parent(node: Element, cls: Any = None) -> Iterable[Element]: node = node.parent -def get_prev_node(node: Node) -> Node: +def get_prev_node(node: Node) -> Optional[Node]: pos = node.parent.index(node) if pos > 0: return node.parent[pos - 1] @@ -360,10 +361,11 @@ indextypes = [ ] -def process_index_entry(entry: str, targetid: str) -> List[Tuple[str, str, str, str, str]]: +def process_index_entry(entry: str, targetid: str + ) -> List[Tuple[str, str, str, str, Optional[str]]]: from sphinx.domains.python import pairindextypes - indexentries: List[Tuple[str, str, str, str, str]] = [] + indexentries: List[Tuple[str, str, str, str, Optional[str]]] = [] entry = entry.strip() oentry = entry main = '' @@ -531,7 +533,8 @@ def make_id(env: "BuildEnvironment", document: nodes.document, return node_id -def find_pending_xref_condition(node: addnodes.pending_xref, condition: str) -> Element: +def find_pending_xref_condition(node: addnodes.pending_xref, condition: str + ) -> Optional[Element]: """Pick matched pending_xref_condition node up from the pending_xref.""" for subnode in node: if (isinstance(subnode, addnodes.pending_xref_condition) and diff --git a/sphinx/util/parallel.py b/sphinx/util/parallel.py index 2d6b4bddb..2a83d6297 100644 --- a/sphinx/util/parallel.py +++ b/sphinx/util/parallel.py @@ -14,7 +14,7 @@ import sys import time import traceback from math import sqrt -from typing import Any, Callable, Dict, List, Sequence +from typing import Any, Callable, Dict, List, Optional, Sequence try: import multiprocessing @@ -62,7 +62,7 @@ class ParallelTasks: # (optional) function performed by each task on the result of main task self._result_funcs: Dict[int, Callable] = {} # task arguments - self._args: Dict[int, List[Any]] = {} + self._args: Dict[int, Optional[List[Any]]] = {} # list of subprocesses (both started and waiting) self._procs: Dict[int, multiprocessing.Process] = {} # list of receiving pipe connections of running subprocesses diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py index 957f8a332..fb8daa623 100644 --- a/sphinx/util/typing.py +++ b/sphinx/util/typing.py @@ -64,7 +64,7 @@ RoleFunction = Callable[[str, str, str, int, Inliner, Dict[str, Any], List[str]] Tuple[List[nodes.Node], List[nodes.system_message]]] # A option spec for directive -OptionSpec = Dict[str, Callable[[Optional[str]], Any]] +OptionSpec = Dict[str, Callable[[str], Any]] # title getter functions for enumerable nodes (see sphinx.domains.std) TitleGetter = Callable[[nodes.Node], str] |
