Fix some static typing errors (#10745)

This commit is contained in:
danieleades 2022-08-14 15:27:16 +01:00 committed by GitHub
parent ee48589fc0
commit c3d8a7d50b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 60 additions and 42 deletions

View File

@ -53,15 +53,9 @@ strict_optional = False
[mypy-sphinx.builders.linkcheck]
strict_optional = False
[mypy-sphinx.builders.singlehtml]
strict_optional = False
[mypy-sphinx.cmd.*]
strict_optional = False
[mypy-sphinx.directives]
strict_optional = False
[mypy-sphinx.directives.code]
strict_optional = False
@ -74,9 +68,6 @@ strict_optional = False
[mypy-sphinx.ext.*]
strict_optional = False
[mypy-sphinx.locale]
strict_optional = False
[mypy-sphinx.pycode.parser]
strict_optional = False

View File

@ -447,7 +447,7 @@ class StandaloneHTMLBuilder(Builder):
def get_asset_paths(self) -> List[str]:
return self.config.html_extra_path + self.config.html_static_path
def render_partial(self, node: Node) -> Dict[str, str]:
def render_partial(self, node: Optional[Node]) -> Dict[str, str]:
"""Utility: Render a lone doctree node."""
if node is None:
return {'fragment': ''}

View File

@ -1,7 +1,7 @@
"""Handlers for additional ReST directives."""
import re
from typing import TYPE_CHECKING, Any, Dict, Generic, List, Tuple, TypeVar, cast
from typing import TYPE_CHECKING, Any, Dict, Generic, List, Optional, Tuple, TypeVar, cast
from docutils import nodes
from docutils.nodes import Node
@ -55,9 +55,9 @@ class ObjectDescription(SphinxDirective, Generic[T]):
# types of doc fields that this directive handles, see sphinx.util.docfields
doc_field_types: List[Field] = []
domain: str = None
objtype: str = None
indexnode: addnodes.index = None
domain: Optional[str] = None
objtype: Optional[str] = None
indexnode: Optional[addnodes.index] = None
# Warning: this might be removed in future version. Don't touch this from extensions.
_doc_field_type_map: Dict[str, Tuple[Field, bool]] = {}

View File

@ -140,7 +140,7 @@ def init(locale_dirs: List[Optional[str]], language: Optional[str],
return translator, has_translation
def setlocale(category: int, value: Union[str, Iterable[str]] = None) -> None:
def setlocale(category: int, value: Union[str, Iterable[str], None] = None) -> None:
"""Update locale settings.
This does not throw any exception even if update fails.

View File

@ -29,7 +29,7 @@ def get_assign_targets(node: ast.AST) -> List[ast.expr]:
return [node.target] # type: ignore
def get_lvar_names(node: ast.AST, self: ast.arg = None) -> List[str]:
def get_lvar_names(node: ast.AST, self: Optional[ast.arg] = None) -> List[str]:
"""Convert assignment-AST to variable names.
This raises `TypeError` if the assignment does not create new variable::
@ -128,7 +128,7 @@ class TokenProcessor:
"""Returns specified line."""
return self.buffers[lineno - 1]
def fetch_token(self) -> Token:
def fetch_token(self) -> Optional[Token]:
"""Fetch the next token from source code.
Returns ``None`` if sequence finished.

View File

@ -154,7 +154,7 @@ class SphinxComponentRegistry:
self.load_extension(app, entry_point.module)
def create_builder(self, app: "Sphinx", name: str,
env: BuildEnvironment = None) -> Builder:
env: Optional[BuildEnvironment] = None) -> Builder:
if name not in self.builders:
raise SphinxError(__('Builder name %s not registered') % name)
@ -228,10 +228,17 @@ class SphinxComponentRegistry:
(index.name, domain))
indices.append(index)
def add_object_type(self, directivename: str, rolename: str, indextemplate: str = '',
parse_node: Callable = None, ref_nodeclass: Type[TextElement] = None,
objname: str = '', doc_field_types: List = [], override: bool = False
) -> None:
def add_object_type(
self,
directivename: str,
rolename: str,
indextemplate: str = '',
parse_node: Optional[Callable] = None,
ref_nodeclass: Optional[Type[TextElement]] = None,
objname: str = '',
doc_field_types: List = [],
override: bool = False
) -> None:
logger.debug('[app] adding object type: %r',
(directivename, rolename, indextemplate, parse_node,
ref_nodeclass, objname, doc_field_types))
@ -252,9 +259,15 @@ class SphinxComponentRegistry:
directivename)
object_types[directivename] = ObjType(objname or directivename, rolename)
def add_crossref_type(self, directivename: str, rolename: str, indextemplate: str = '',
ref_nodeclass: Type[TextElement] = None, objname: str = '',
override: bool = False) -> None:
def add_crossref_type(
self,
directivename: str,
rolename: str,
indextemplate: str = '',
ref_nodeclass: Optional[Type[TextElement]] = None,
objname: str = '',
override: bool = False
) -> None:
logger.debug('[app] adding crossref type: %r',
(directivename, rolename, indextemplate, ref_nodeclass, objname))
@ -404,8 +417,13 @@ class SphinxComponentRegistry:
else:
self.latex_packages.append((name, options))
def add_enumerable_node(self, node: Type[Node], figtype: str,
title_getter: TitleGetter = None, override: bool = False) -> None:
def add_enumerable_node(
self,
node: Type[Node],
figtype: str,
title_getter: Optional[TitleGetter] = None,
override: bool = False
) -> None:
logger.debug('[app] adding enumerable node: (%r, %r, %r)', node, figtype, title_getter)
if node in self.enumerable_nodes and not override:
raise ExtensionError(__('enumerable_node %r already registered') % node)

View File

@ -6,7 +6,7 @@ import re
import warnings
from importlib import import_module
from os import path
from typing import IO, Any, Dict, Iterable, List, Optional, Set, Tuple, Type
from typing import IO, Any, Dict, Iterable, List, Optional, Set, Tuple, Type, Union
from docutils import nodes
from docutils.nodes import Element, Node
@ -46,11 +46,11 @@ class SearchLanguage:
This class is used to preprocess search word which Sphinx HTML readers
type, before searching index. Default implementation does nothing.
"""
lang: str = None
language_name: str = None
lang: Optional[str] = None
language_name: Optional[str] = None
stopwords: Set[str] = set()
js_splitter_code: str = ""
js_stemmer_rawcode: str = None
js_stemmer_rawcode: Optional[str] = None
js_stemmer_code = """
/**
* Dummy stemmer for languages without stemming rules.
@ -125,7 +125,7 @@ def parse_stop_word(source: str) -> Set[str]:
# maps language name to module.class or directly a class
languages: Dict[str, Any] = {
languages: Dict[str, Union[str, Type[SearchLanguage]]] = {
'da': 'sphinx.search.da.SearchDanish',
'de': 'sphinx.search.de.SearchGerman',
'en': SearchEnglish,
@ -242,7 +242,7 @@ class IndexBuilder:
# objtype index -> (domain, type, objname (localized))
self._objnames: Dict[int, Tuple[str, str, str]] = {}
# add language-specific SearchLanguage instance
lang_class: Type[SearchLanguage] = languages.get(lang)
lang_class = languages.get(lang)
# fallback; try again with language-code
if lang_class is None and '_' in lang:
@ -252,8 +252,8 @@ class IndexBuilder:
self.lang: SearchLanguage = SearchEnglish(options)
elif isinstance(lang_class, str):
module, classname = lang_class.rsplit('.', 1)
lang_class = getattr(import_module(module), classname)
self.lang = lang_class(options)
lang_class: Type[SearchLanguage] = getattr(import_module(module), classname) # type: ignore[no-redef]
self.lang = lang_class(options) # type: ignore[operator]
else:
# it's directly a class (e.g. added by app.add_search_language)
self.lang = lang_class(options)

View File

@ -5,7 +5,7 @@ import re
import sys
import warnings
from io import StringIO
from typing import IO, Any, Dict, Generator, List, Pattern
from typing import IO, Any, Dict, Generator, List, Optional, Pattern
from xml.etree import ElementTree
from docutils import nodes
@ -94,10 +94,19 @@ class SphinxTestApp(application.Sphinx):
_status: StringIO = None
_warning: StringIO = None
def __init__(self, buildername: str = 'html', srcdir: path = None, builddir: path = None,
freshenv: bool = False, confoverrides: Dict = None, status: IO = None,
warning: IO = None, tags: List[str] = None, docutilsconf: str = None,
parallel: int = 0) -> None:
def __init__(
self,
buildername: str = 'html',
srcdir: Optional[path] = None,
builddir: Optional[path] = None,
freshenv: bool = False,
confoverrides: Optional[Dict] = None,
status: Optional[IO] = None,
warning: Optional[IO] = None,
tags: Optional[List[str]] = None,
docutilsconf: Optional[str] = None,
parallel: int = 0
) -> None:
if docutilsconf is not None:
(srcdir / 'docutils.conf').write_text(docutilsconf)
@ -169,10 +178,10 @@ class SphinxTestAppWrapperForSkipBuilding:
_unicode_literals_re = re.compile(r'u(".*?")|u(\'.*?\')')
def find_files(root: str, suffix: bool = None) -> Generator[str, None, None]:
def find_files(root: str, suffix: Optional[str] = None) -> Generator[str, None, None]:
for dirpath, _dirs, files in os.walk(root, followlinks=True):
dirpath = path(dirpath)
for f in [f for f in files if not suffix or f.endswith(suffix)]: # type: ignore
for f in [f for f in files if not suffix or f.endswith(suffix)]:
fpath = dirpath / f
yield relpath(fpath, root)