refactor: Use PEP-526 based variable annotation (sphinx.builders)

This commit is contained in:
Takeshi KOMIYA
2021-03-13 16:30:59 +09:00
parent c817c20626
commit aeb9e42d2b
16 changed files with 98 additions and 100 deletions

View File

@@ -63,7 +63,7 @@ class Builder:
#: default translator class for the builder. This can be overridden by #: default translator class for the builder. This can be overridden by
#: :py:meth:`app.set_translator()`. #: :py:meth:`app.set_translator()`.
default_translator_class = None # type: Type[nodes.NodeVisitor] default_translator_class: Type[nodes.NodeVisitor] = None
# doctree versioning method # doctree versioning method
versioning_method = 'none' versioning_method = 'none'
versioning_compare = False versioning_compare = False
@@ -74,7 +74,7 @@ class Builder:
#: The list of MIME types of image formats supported by the builder. #: The list of MIME types of image formats supported by the builder.
#: Image files are searched in the order in which they appear here. #: Image files are searched in the order in which they appear here.
supported_image_types = [] # type: List[str] supported_image_types: List[str] = []
#: The builder supports remote images or not. #: The builder supports remote images or not.
supported_remote_images = False supported_remote_images = False
#: The builder supports data URIs or not. #: The builder supports data URIs or not.
@@ -87,18 +87,18 @@ class Builder:
self.doctreedir = app.doctreedir self.doctreedir = app.doctreedir
ensuredir(self.doctreedir) ensuredir(self.doctreedir)
self.app = app # type: Sphinx self.app: Sphinx = app
self.env = None # type: BuildEnvironment self.env: BuildEnvironment = None
self.events = app.events # type: EventManager self.events: EventManager = app.events
self.config = app.config # type: Config self.config: Config = app.config
self.tags = app.tags # type: Tags self.tags: Tags = app.tags
self.tags.add(self.format) self.tags.add(self.format)
self.tags.add(self.name) self.tags.add(self.name)
self.tags.add("format_%s" % self.format) self.tags.add("format_%s" % self.format)
self.tags.add("builder_%s" % self.name) self.tags.add("builder_%s" % self.name)
# images that need to be copied over (source -> dest) # images that need to be copied over (source -> dest)
self.images = {} # type: Dict[str, str] self.images: Dict[str, str] = {}
# basename of images directory # basename of images directory
self.imagedir = "" self.imagedir = ""
# relative path to image directory from current docname (used at writing docs) # relative path to image directory from current docname (used at writing docs)
@@ -106,7 +106,7 @@ class Builder:
# these get set later # these get set later
self.parallel_ok = False self.parallel_ok = False
self.finish_tasks = None # type: Any self.finish_tasks: Any = None
def set_environment(self, env: BuildEnvironment) -> None: def set_environment(self, env: BuildEnvironment) -> None:
"""Store BuildEnvironment object.""" """Store BuildEnvironment object."""
@@ -261,8 +261,7 @@ class Builder:
# relative to the source directory and without source_suffix. # relative to the source directory and without source_suffix.
dirlen = len(self.srcdir) + 1 dirlen = len(self.srcdir) + 1
to_write = [] to_write = []
suffixes = None # type: Tuple[str] suffixes: Tuple[str] = tuple(self.config.source_suffix) # type: ignore
suffixes = tuple(self.config.source_suffix) # type: ignore
for filename in filenames: for filename in filenames:
filename = path.normpath(path.abspath(filename)) filename = path.normpath(path.abspath(filename))
if not filename.startswith(self.srcdir): if not filename.startswith(self.srcdir):

View File

@@ -165,9 +165,9 @@ class EpubBuilder(StandaloneHTMLBuilder):
self.link_suffix = '.xhtml' self.link_suffix = '.xhtml'
self.playorder = 0 self.playorder = 0
self.tocid = 0 self.tocid = 0
self.id_cache = {} # type: Dict[str, str] self.id_cache: Dict[str, str] = {}
self.use_index = self.get_builder_config('use_index', 'epub') self.use_index = self.get_builder_config('use_index', 'epub')
self.refnodes = [] # type: List[Dict[str, Any]] self.refnodes: List[Dict[str, Any]] = []
def create_build_info(self) -> BuildInfo: def create_build_info(self) -> BuildInfo:
return BuildInfo(self.config, self.tags, ['html', 'epub']) return BuildInfo(self.config, self.tags, ['html', 'epub'])
@@ -209,7 +209,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
return result return result
def check_refnodes(self, nodes: List[Dict[str, Any]]) -> None: def check_refnodes(self, nodes: List[Dict[str, Any]]) -> None:
appeared = set() # type: Set[str] appeared: Set[str] = set()
for node in nodes: for node in nodes:
if node['refuri'] in appeared: if node['refuri'] in appeared:
logger.warning( logger.warning(
@@ -288,7 +288,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
for target in tree.traverse(nodes.target): for target in tree.traverse(nodes.target):
update_node_id(target) update_node_id(target)
next_node = target.next_node(ascend=True) # type: Node next_node: Node = target.next_node(ascend=True)
if isinstance(next_node, nodes.Element): if isinstance(next_node, nodes.Element):
update_node_id(next_node) update_node_id(next_node)
@@ -482,7 +482,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
"""Create a dictionary with all metadata for the content.opf """Create a dictionary with all metadata for the content.opf
file properly escaped. file properly escaped.
""" """
metadata = {} # type: Dict[str, Any] metadata: Dict[str, Any] = {}
metadata['title'] = html.escape(self.config.epub_title) metadata['title'] = html.escape(self.config.epub_title)
metadata['author'] = html.escape(self.config.epub_author) metadata['author'] = html.escape(self.config.epub_author)
metadata['uid'] = html.escape(self.config.epub_uid) metadata['uid'] = html.escape(self.config.epub_uid)
@@ -508,7 +508,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
if not self.outdir.endswith(os.sep): if not self.outdir.endswith(os.sep):
self.outdir += os.sep self.outdir += os.sep
olen = len(self.outdir) olen = len(self.outdir)
self.files = [] # type: List[str] self.files: List[str] = []
self.ignored_files = ['.buildinfo', 'mimetype', 'content.opf', self.ignored_files = ['.buildinfo', 'mimetype', 'content.opf',
'toc.ncx', 'META-INF/container.xml', 'toc.ncx', 'META-INF/container.xml',
'Thumbs.db', 'ehthumbs.db', '.DS_Store', 'Thumbs.db', 'ehthumbs.db', '.DS_Store',
@@ -623,7 +623,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
Subelements of a node are nested inside the navpoint. For nested nodes Subelements of a node are nested inside the navpoint. For nested nodes
the parent node is reinserted in the subnav. the parent node is reinserted in the subnav.
""" """
navstack = [] # type: List[NavPoint] navstack: List[NavPoint] = []
navstack.append(NavPoint('dummy', 0, '', '', [])) navstack.append(NavPoint('dummy', 0, '', '', []))
level = 0 level = 0
lastnode = None lastnode = None
@@ -665,7 +665,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
"""Create a dictionary with all metadata for the toc.ncx file """Create a dictionary with all metadata for the toc.ncx file
properly escaped. properly escaped.
""" """
metadata = {} # type: Dict[str, Any] metadata: Dict[str, Any] = {}
metadata['uid'] = self.config.epub_uid metadata['uid'] = self.config.epub_uid
metadata['title'] = html.escape(self.config.epub_title) metadata['title'] = html.escape(self.config.epub_title)
metadata['level'] = level metadata['level'] = level

View File

@@ -51,9 +51,9 @@ class ChangesBuilder(Builder):
def write(self, *ignored: Any) -> None: def write(self, *ignored: Any) -> None:
version = self.config.version version = self.config.version
domain = cast(ChangeSetDomain, self.env.get_domain('changeset')) domain = cast(ChangeSetDomain, self.env.get_domain('changeset'))
libchanges = {} # type: Dict[str, List[Tuple[str, str, int]]] libchanges: Dict[str, List[Tuple[str, str, int]]] = {}
apichanges = [] # type: List[Tuple[str, str, int]] apichanges: List[Tuple[str, str, int]] = []
otherchanges = {} # type: Dict[Tuple[str, str], List[Tuple[str, str, int]]] otherchanges: Dict[Tuple[str, str], List[Tuple[str, str, int]]] = {}
changesets = domain.get_changesets_for(version) changesets = domain.get_changesets_for(version)
if not changesets: if not changesets:

View File

@@ -118,7 +118,7 @@ class Epub3Builder(_epub_base.EpubBuilder):
The difference from build_navpoints method is templates which are used The difference from build_navpoints method is templates which are used
when generating navigation documents. when generating navigation documents.
""" """
navstack = [] # type: List[NavPoint] navstack: List[NavPoint] = []
navstack.append(NavPoint('', '', [])) navstack.append(NavPoint('', '', []))
level = 0 level = 0
for node in navnodes: for node in navnodes:
@@ -154,7 +154,7 @@ class Epub3Builder(_epub_base.EpubBuilder):
"""Create a dictionary with all metadata for the nav.xhtml file """Create a dictionary with all metadata for the nav.xhtml file
properly escaped. properly escaped.
""" """
metadata = {} # type: Dict metadata: Dict = {}
metadata['lang'] = html.escape(self.config.epub_language) metadata['lang'] = html.escape(self.config.epub_language)
metadata['toc_locale'] = html.escape(self.guide_titles['toc']) metadata['toc_locale'] = html.escape(self.guide_titles['toc'])
metadata['navlist'] = navlist metadata['navlist'] = navlist
@@ -223,7 +223,7 @@ def validate_config_values(app: Sphinx) -> None:
def convert_epub_css_files(app: Sphinx, config: Config) -> None: def convert_epub_css_files(app: Sphinx, config: Config) -> None:
"""This converts string styled epub_css_files to tuple styled one.""" """This converts string styled epub_css_files to tuple styled one."""
epub_css_files = [] # type: List[Tuple[str, Dict]] epub_css_files: List[Tuple[str, Dict]] = []
for entry in config.epub_css_files: for entry in config.epub_css_files:
if isinstance(entry, str): if isinstance(entry, str):
epub_css_files.append((entry, {})) epub_css_files.append((entry, {}))

View File

@@ -48,10 +48,10 @@ class Catalog:
"""Catalog of translatable messages.""" """Catalog of translatable messages."""
def __init__(self) -> None: def __init__(self) -> None:
self.messages = [] # type: List[str] self.messages: List[str] = [] # retain insertion order, a la OrderedDict
# retain insertion order, a la OrderedDict
self.metadata = OrderedDict() # type: Dict[str, List[Tuple[str, int, str]]]
# msgid -> file, line, uid # msgid -> file, line, uid
self.metadata: Dict[str, List[Tuple[str, int, str]]] = OrderedDict()
def add(self, msg: str, origin: Union[Element, "MsgOrigin"]) -> None: def add(self, msg: str, origin: Union[Element, "MsgOrigin"]) -> None:
if not hasattr(origin, 'uid'): if not hasattr(origin, 'uid'):
@@ -121,8 +121,7 @@ class I18nBuilder(Builder):
""" """
name = 'i18n' name = 'i18n'
versioning_method = 'text' versioning_method = 'text'
versioning_compare = None # type: bool versioning_compare: bool = None # be set by `gettext_uuid`
# be set by `gettext_uuid`
use_message_catalog = False use_message_catalog = False
def init(self) -> None: def init(self) -> None:
@@ -130,7 +129,7 @@ class I18nBuilder(Builder):
self.env.set_versioning_method(self.versioning_method, self.env.set_versioning_method(self.versioning_method,
self.env.config.gettext_uuid) self.env.config.gettext_uuid)
self.tags = I18nTags() self.tags = I18nTags()
self.catalogs = defaultdict(Catalog) # type: DefaultDict[str, Catalog] self.catalogs: DefaultDict[str, Catalog] = defaultdict(Catalog)
def get_target_uri(self, docname: str, typ: str = None) -> str: def get_target_uri(self, docname: str, typ: str = None) -> str:
return '' return ''

View File

@@ -82,9 +82,9 @@ class Stylesheet(str):
its filename (str). its filename (str).
""" """
attributes = None # type: Dict[str, str] attributes: Dict[str, str] = None
filename = None # type: str filename: str = None
priority = None # type: int priority: int = None
def __new__(cls, filename: str, *args: str, priority: int = 500, **attributes: Any def __new__(cls, filename: str, *args: str, priority: int = 500, **attributes: Any
) -> "Stylesheet": ) -> "Stylesheet":
@@ -108,9 +108,9 @@ class JavaScript(str):
its filename (str). its filename (str).
""" """
attributes = None # type: Dict[str, str] attributes: Dict[str, str] = None
filename = None # type: str filename: str = None
priority = None # type: int priority: int = None
def __new__(cls, filename: str, priority: int = 500, **attributes: str) -> "JavaScript": def __new__(cls, filename: str, priority: int = 500, **attributes: str) -> "JavaScript":
self = str.__new__(cls, filename) self = str.__new__(cls, filename)
@@ -179,7 +179,7 @@ class StandaloneHTMLBuilder(Builder):
allow_parallel = True allow_parallel = True
out_suffix = '.html' out_suffix = '.html'
link_suffix = '.html' # defaults to matching out_suffix link_suffix = '.html' # defaults to matching out_suffix
indexer_format = js_index # type: Any indexer_format: Any = js_index
indexer_dumps_unicode = True indexer_dumps_unicode = True
# create links to original images from images [True/False] # create links to original images from images [True/False]
html_scaled_image_link = True html_scaled_image_link = True
@@ -195,26 +195,26 @@ class StandaloneHTMLBuilder(Builder):
use_index = False use_index = False
download_support = True # enable download role download_support = True # enable download role
imgpath = None # type: str imgpath: str = None
domain_indices = [] # type: List[Tuple[str, Type[Index], List[Tuple[str, List[IndexEntry]]], bool]] # NOQA domain_indices: List[Tuple[str, Type[Index], List[Tuple[str, List[IndexEntry]]], bool]] = [] # NOQA
def __init__(self, app: Sphinx) -> None: def __init__(self, app: Sphinx) -> None:
super().__init__(app) super().__init__(app)
# CSS files # CSS files
self.css_files = [] # type: List[Dict[str, str]] self.css_files: List[Dict[str, str]] = []
# JS files # JS files
self.script_files = [] # type: List[JavaScript] self.script_files: List[JavaScript] = []
def init(self) -> None: def init(self) -> None:
self.build_info = self.create_build_info() self.build_info = self.create_build_info()
# basename of images directory # basename of images directory
self.imagedir = '_images' self.imagedir = '_images'
# section numbers for headings in the currently visited document # section numbers for headings in the currently visited document
self.secnumbers = {} # type: Dict[str, Tuple[int, ...]] self.secnumbers: Dict[str, Tuple[int, ...]] = {}
# currently written docname # currently written docname
self.current_docname = None # type: str self.current_docname: str = None
self.init_templates() self.init_templates()
self.init_highlighter() self.init_highlighter()
@@ -436,10 +436,10 @@ class StandaloneHTMLBuilder(Builder):
self.load_indexer(docnames) self.load_indexer(docnames)
self.docwriter = HTMLWriter(self) self.docwriter = HTMLWriter(self)
self.docsettings = OptionParser( self.docsettings: Any = OptionParser(
defaults=self.env.settings, defaults=self.env.settings,
components=(self.docwriter,), components=(self.docwriter,),
read_config_files=True).get_default_values() # type: Any read_config_files=True).get_default_values()
self.docsettings.compact_lists = bool(self.config.html_compact_lists) self.docsettings.compact_lists = bool(self.config.html_compact_lists)
# determine the additional indices to include # determine the additional indices to include
@@ -448,8 +448,7 @@ class StandaloneHTMLBuilder(Builder):
indices_config = self.config.html_domain_indices indices_config = self.config.html_domain_indices
if indices_config: if indices_config:
for domain_name in sorted(self.env.domains): for domain_name in sorted(self.env.domains):
domain = None # type: Domain domain: Domain = self.env.domains[domain_name]
domain = self.env.domains[domain_name]
for indexcls in domain.indices: for indexcls in domain.indices:
indexname = '%s-%s' % (domain.name, indexcls.name) indexname = '%s-%s' % (domain.name, indexcls.name)
if isinstance(indices_config, list): if isinstance(indices_config, list):
@@ -474,7 +473,7 @@ class StandaloneHTMLBuilder(Builder):
self.relations = self.env.collect_relations() self.relations = self.env.collect_relations()
rellinks = [] # type: List[Tuple[str, str, str, str]] rellinks: List[Tuple[str, str, str, str]] = []
if self.use_index: if self.use_index:
rellinks.append(('genindex', _('General Index'), 'I', _('index'))) rellinks.append(('genindex', _('General Index'), 'I', _('index')))
for indexname, indexcls, content, collapse in self.domain_indices: for indexname, indexcls, content, collapse in self.domain_indices:
@@ -1109,7 +1108,7 @@ class StandaloneHTMLBuilder(Builder):
def convert_html_css_files(app: Sphinx, config: Config) -> None: def convert_html_css_files(app: Sphinx, config: Config) -> None:
"""This converts string styled html_css_files to tuple styled one.""" """This converts string styled html_css_files to tuple styled one."""
html_css_files = [] # type: List[Tuple[str, Dict]] html_css_files: List[Tuple[str, Dict]] = []
for entry in config.html_css_files: for entry in config.html_css_files:
if isinstance(entry, str): if isinstance(entry, str):
html_css_files.append((entry, {})) html_css_files.append((entry, {}))
@@ -1126,7 +1125,7 @@ def convert_html_css_files(app: Sphinx, config: Config) -> None:
def convert_html_js_files(app: Sphinx, config: Config) -> None: def convert_html_js_files(app: Sphinx, config: Config) -> None:
"""This converts string styled html_js_files to tuple styled one.""" """This converts string styled html_js_files to tuple styled one."""
html_js_files = [] # type: List[Tuple[str, Dict]] html_js_files: List[Tuple[str, Dict]] = []
for entry in config.html_js_files: for entry in config.html_js_files:
if isinstance(entry, str): if isinstance(entry, str):
html_js_files.append((entry, {})) html_js_files.append((entry, {}))

View File

@@ -122,10 +122,10 @@ class LaTeXBuilder(Builder):
default_translator_class = LaTeXTranslator default_translator_class = LaTeXTranslator
def init(self) -> None: def init(self) -> None:
self.babel = None # type: ExtBabel self.babel: ExtBabel = None
self.context = {} # type: Dict[str, Any] self.context: Dict[str, Any] = {}
self.docnames = [] # type: Iterable[str] self.docnames: Iterable[str] = {}
self.document_data = [] # type: List[Tuple[str, str, str, str, str, bool]] self.document_data: List[Tuple[str, str, str, str, str, bool]] = []
self.themes = ThemeFactory(self.app) self.themes = ThemeFactory(self.app)
texescape.init() texescape.init()
@@ -153,7 +153,7 @@ class LaTeXBuilder(Builder):
'will be written')) 'will be written'))
return return
# assign subdirs to titles # assign subdirs to titles
self.titles = [] # type: List[Tuple[str, str]] self.titles: List[Tuple[str, str]] = []
for entry in preliminary_document_data: for entry in preliminary_document_data:
docname = entry[0] docname = entry[0]
if docname not in self.env.all_docs: if docname not in self.env.all_docs:
@@ -262,10 +262,10 @@ class LaTeXBuilder(Builder):
def write(self, *ignored: Any) -> None: def write(self, *ignored: Any) -> None:
docwriter = LaTeXWriter(self) docwriter = LaTeXWriter(self)
docsettings = OptionParser( docsettings: Any = OptionParser(
defaults=self.env.settings, defaults=self.env.settings,
components=(docwriter,), components=(docwriter,),
read_config_files=True).get_default_values() # type: Any read_config_files=True).get_default_values()
self.init_document_data() self.init_document_data()
self.write_stylesheet() self.write_stylesheet()
@@ -356,7 +356,7 @@ class LaTeXBuilder(Builder):
for pendingnode in largetree.traverse(addnodes.pending_xref): for pendingnode in largetree.traverse(addnodes.pending_xref):
docname = pendingnode['refdocname'] docname = pendingnode['refdocname']
sectname = pendingnode['refsectname'] sectname = pendingnode['refsectname']
newnodes = [nodes.emphasis(sectname, sectname)] # type: List[Node] newnodes: List[Node] = [nodes.emphasis(sectname, sectname)]
for subdir, title in self.titles: for subdir, title in self.titles:
if docname.startswith(subdir): if docname.startswith(subdir):
newnodes.append(nodes.Text(_(' (in '), _(' (in '))) newnodes.append(nodes.Text(_(' (in '), _(' (in ')))

View File

@@ -71,7 +71,7 @@ XELATEX_GREEK_DEFAULT_FONTPKG = (XELATEX_DEFAULT_FONTPKG +
LUALATEX_DEFAULT_FONTPKG = XELATEX_DEFAULT_FONTPKG LUALATEX_DEFAULT_FONTPKG = XELATEX_DEFAULT_FONTPKG
DEFAULT_SETTINGS = { DEFAULT_SETTINGS: Dict[str, Any] = {
'latex_engine': 'pdflatex', 'latex_engine': 'pdflatex',
'papersize': '', 'papersize': '',
'pointsize': '', 'pointsize': '',
@@ -121,9 +121,9 @@ DEFAULT_SETTINGS = {
'figure_align': 'htbp', 'figure_align': 'htbp',
'tocdepth': '', 'tocdepth': '',
'secnumdepth': '', 'secnumdepth': '',
} # type: Dict[str, Any] }
ADDITIONAL_SETTINGS = { ADDITIONAL_SETTINGS: Dict[Any, Dict[str, Any]] = {
'pdflatex': { 'pdflatex': {
'inputenc': '\\usepackage[utf8]{inputenc}', 'inputenc': '\\usepackage[utf8]{inputenc}',
'utf8extra': ('\\ifdefined\\DeclareUnicodeCharacter\n' 'utf8extra': ('\\ifdefined\\DeclareUnicodeCharacter\n'
@@ -202,7 +202,7 @@ ADDITIONAL_SETTINGS = {
('xelatex', 'el'): { ('xelatex', 'el'): {
'fontpkg': XELATEX_GREEK_DEFAULT_FONTPKG, 'fontpkg': XELATEX_GREEK_DEFAULT_FONTPKG,
}, },
} # type: Dict[Any, Dict[str, Any]] }
SHORTHANDOFF = r''' SHORTHANDOFF = r'''

View File

@@ -106,7 +106,7 @@ class ThemeFactory:
"""A factory class for LaTeX Themes.""" """A factory class for LaTeX Themes."""
def __init__(self, app: Sphinx) -> None: def __init__(self, app: Sphinx) -> None:
self.themes = {} # type: Dict[str, Theme] self.themes: Dict[str, Theme] = {}
self.theme_paths = [path.join(app.srcdir, p) for p in app.config.latex_theme_path] self.theme_paths = [path.join(app.srcdir, p) for p in app.config.latex_theme_path]
self.config = app.config self.config = app.config
self.load_builtin_themes(app.config) self.load_builtin_themes(app.config)

View File

@@ -33,7 +33,7 @@ class FootnoteDocnameUpdater(SphinxTransform):
def apply(self, **kwargs: Any) -> None: def apply(self, **kwargs: Any) -> None:
matcher = NodeMatcher(*self.TARGET_NODES) matcher = NodeMatcher(*self.TARGET_NODES)
for node in self.document.traverse(matcher): # type: nodes.Element for node in self.document.traverse(matcher): # type: Element
node['docname'] = self.env.docname node['docname'] = self.env.docname
@@ -65,7 +65,7 @@ class ShowUrlsTransform(SphinxPostTransform):
def run(self, **kwargs: Any) -> None: def run(self, **kwargs: Any) -> None:
try: try:
# replace id_prefix temporarily # replace id_prefix temporarily
settings = self.document.settings # type: Any settings: Any = self.document.settings
id_prefix = settings.id_prefix id_prefix = settings.id_prefix
settings.id_prefix = 'show_urls' settings.id_prefix = 'show_urls'
@@ -157,9 +157,9 @@ class FootnoteCollector(nodes.NodeVisitor):
"""Collect footnotes and footnote references on the document""" """Collect footnotes and footnote references on the document"""
def __init__(self, document: nodes.document) -> None: def __init__(self, document: nodes.document) -> None:
self.auto_footnotes = [] # type: List[nodes.footnote] self.auto_footnotes: List[nodes.footnote] = []
self.used_footnote_numbers = set() # type: Set[str] self.used_footnote_numbers: Set[str] = set()
self.footnote_refs = [] # type: List[nodes.footnote_reference] self.footnote_refs: List[nodes.footnote_reference] = []
super().__init__(document) super().__init__(document)
def unknown_visit(self, node: Node) -> None: def unknown_visit(self, node: Node) -> None:
@@ -358,11 +358,11 @@ class LaTeXFootnoteTransform(SphinxPostTransform):
class LaTeXFootnoteVisitor(nodes.NodeVisitor): class LaTeXFootnoteVisitor(nodes.NodeVisitor):
def __init__(self, document: nodes.document, footnotes: List[nodes.footnote]) -> None: def __init__(self, document: nodes.document, footnotes: List[nodes.footnote]) -> None:
self.appeared = set() # type: Set[Tuple[str, str]] self.appeared: Set[Tuple[str, str]] = set()
self.footnotes = footnotes # type: List[nodes.footnote] self.footnotes: List[nodes.footnote] = footnotes
self.pendings = [] # type: List[nodes.footnote] self.pendings: List[nodes.footnote] = []
self.table_footnotes = [] # type: List[nodes.footnote] self.table_footnotes: List[nodes.footnote] = []
self.restricted = None # type: nodes.Element self.restricted: Element = None
super().__init__(document) super().__init__(document)
def unknown_visit(self, node: Node) -> None: def unknown_visit(self, node: Node) -> None:

View File

@@ -9,7 +9,6 @@
""" """
import json import json
import queue
import re import re
import socket import socket
import time import time
@@ -18,6 +17,7 @@ from datetime import datetime, timezone
from email.utils import parsedate_to_datetime from email.utils import parsedate_to_datetime
from html.parser import HTMLParser from html.parser import HTMLParser
from os import path from os import path
from queue import PriorityQueue, Queue
from threading import Thread from threading import Thread
from typing import (Any, Dict, Generator, List, NamedTuple, Optional, Pattern, Set, Tuple, from typing import (Any, Dict, Generator, List, NamedTuple, Optional, Pattern, Set, Tuple,
Union, cast) Union, cast)
@@ -120,16 +120,16 @@ class CheckExternalLinksBuilder(DummyBuilder):
'%(outdir)s/output.txt') '%(outdir)s/output.txt')
def init(self) -> None: def init(self) -> None:
self.hyperlinks = {} # type: Dict[str, Hyperlink] self.hyperlinks: Dict[str, Hyperlink] = {}
self._good = set() # type: Set[str] self._good: Set[str] = set()
self._broken = {} # type: Dict[str, str] self._broken: Dict[str, str] = {}
self._redirected = {} # type: Dict[str, Tuple[str, int]] self._redirected: Dict[str, Tuple[str, int]] = {}
# set a timeout for non-responding servers # set a timeout for non-responding servers
socket.setdefaulttimeout(5.0) socket.setdefaulttimeout(5.0)
# create queues and worker threads # create queues and worker threads
self._wqueue = queue.PriorityQueue() # type: queue.PriorityQueue[CheckRequestType] self._wqueue: PriorityQueue[CheckRequestType] = PriorityQueue()
self._rqueue = queue.Queue() # type: queue.Queue self._rqueue: Queue = Queue()
@property @property
def anchors_ignore(self) -> List[Pattern]: def anchors_ignore(self) -> List[Pattern]:
@@ -204,7 +204,7 @@ class CheckExternalLinksBuilder(DummyBuilder):
None, None, {}) None, None, {})
return worker.limit_rate(response) return worker.limit_rate(response)
def rqueue(self, response: Response) -> queue.Queue: def rqueue(self, response: Response) -> Queue:
warnings.warn( warnings.warn(
"%s.%s is deprecated." % (self.__class__.__name__, "rqueue"), "%s.%s is deprecated." % (self.__class__.__name__, "rqueue"),
RemovedInSphinx50Warning, RemovedInSphinx50Warning,
@@ -220,7 +220,7 @@ class CheckExternalLinksBuilder(DummyBuilder):
) )
return [] return []
def wqueue(self, response: Response) -> queue.Queue: def wqueue(self, response: Response) -> Queue:
warnings.warn( warnings.warn(
"%s.%s is deprecated." % (self.__class__.__name__, "wqueue"), "%s.%s is deprecated." % (self.__class__.__name__, "wqueue"),
RemovedInSphinx50Warning, RemovedInSphinx50Warning,
@@ -313,8 +313,8 @@ class HyperlinkAvailabilityChecker:
self.builder = builder self.builder = builder
self.config = config self.config = config
self.env = env self.env = env
self.rate_limits = {} # type: Dict[str, RateLimit] self.rate_limits: Dict[str, RateLimit] = {}
self.workers = [] # type: List[Thread] self.workers: List[Thread] = []
self.to_ignore = [re.compile(x) for x in self.config.linkcheck_ignore] self.to_ignore = [re.compile(x) for x in self.config.linkcheck_ignore]
@@ -322,8 +322,8 @@ class HyperlinkAvailabilityChecker:
self.rqueue = builder._rqueue self.rqueue = builder._rqueue
self.wqueue = builder._wqueue self.wqueue = builder._wqueue
else: else:
self.rqueue = queue.Queue() self.rqueue = Queue()
self.wqueue = queue.PriorityQueue() self.wqueue = PriorityQueue()
def invoke_threads(self) -> None: def invoke_threads(self) -> None:
for i in range(self.config.linkcheck_workers): for i in range(self.config.linkcheck_workers):
@@ -364,8 +364,8 @@ class HyperlinkAvailabilityChecker:
class HyperlinkAvailabilityCheckWorker(Thread): class HyperlinkAvailabilityCheckWorker(Thread):
"""A worker class for checking the availability of hyperlinks.""" """A worker class for checking the availability of hyperlinks."""
def __init__(self, env: BuildEnvironment, config: Config, rqueue: queue.Queue, def __init__(self, env: BuildEnvironment, config: Config, rqueue: Queue,
wqueue: queue.Queue, rate_limits: Dict[str, RateLimit], wqueue: Queue, rate_limits: Dict[str, RateLimit],
builder: CheckExternalLinksBuilder = None) -> None: builder: CheckExternalLinksBuilder = None) -> None:
# Warning: builder argument will be removed in the sphinx-5.0. # Warning: builder argument will be removed in the sphinx-5.0.
# Don't use it from extensions. # Don't use it from extensions.

View File

@@ -38,7 +38,7 @@ class ManualPageBuilder(Builder):
epilog = __('The manual pages are in %(outdir)s.') epilog = __('The manual pages are in %(outdir)s.')
default_translator_class = ManualPageTranslator default_translator_class = ManualPageTranslator
supported_image_types = [] # type: List[str] supported_image_types: List[str] = []
def init(self) -> None: def init(self) -> None:
if not self.config.man_pages: if not self.config.man_pages:
@@ -56,10 +56,10 @@ class ManualPageBuilder(Builder):
@progress_message(__('writing')) @progress_message(__('writing'))
def write(self, *ignored: Any) -> None: def write(self, *ignored: Any) -> None:
docwriter = ManualPageWriter(self) docwriter = ManualPageWriter(self)
docsettings = OptionParser( docsettings: Any = OptionParser(
defaults=self.env.settings, defaults=self.env.settings,
components=(docwriter,), components=(docwriter,),
read_config_files=True).get_default_values() # type: Any read_config_files=True).get_default_values()
for info in self.config.man_pages: for info in self.config.man_pages:
docname, name, description, authors, section = info docname, name, description, authors, section = info
@@ -90,7 +90,7 @@ class ManualPageBuilder(Builder):
encoding='utf-8') encoding='utf-8')
tree = self.env.get_doctree(docname) tree = self.env.get_doctree(docname)
docnames = set() # type: Set[str] docnames: Set[str] = set()
largetree = inline_all_toctrees(self, docnames, docname, tree, largetree = inline_all_toctrees(self, docnames, docname, tree,
darkgreen, [docname]) darkgreen, [docname])
largetree.settings = docsettings largetree.settings = docsettings

View File

@@ -93,7 +93,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder):
# #
# There are related codes in inline_all_toctres() and # There are related codes in inline_all_toctres() and
# HTMLTranslter#add_secnumber(). # HTMLTranslter#add_secnumber().
new_secnumbers = {} # type: Dict[str, Tuple[int, ...]] new_secnumbers: Dict[str, Tuple[int, ...]] = {}
for docname, secnums in self.env.toc_secnumbers.items(): for docname, secnums in self.env.toc_secnumbers.items():
for id, secnum in secnums.items(): for id, secnum in secnums.items():
alias = "%s/%s" % (docname, id) alias = "%s/%s" % (docname, id)
@@ -111,7 +111,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder):
# #
# There are related codes in inline_all_toctres() and # There are related codes in inline_all_toctres() and
# HTMLTranslter#add_fignumber(). # HTMLTranslter#add_fignumber().
new_fignumbers = {} # type: Dict[str, Dict[str, Tuple[int, ...]]] new_fignumbers: Dict[str, Dict[str, Tuple[int, ...]]] = {}
# {'foo': {'figure': {'id2': (2,), 'id1': (1,)}}, 'bar': {'figure': {'id1': (3,)}}} # {'foo': {'figure': {'id2': (2,), 'id1': (1,)}}, 'bar': {'figure': {'id1': (3,)}}}
for docname, fignumlist in self.env.toc_fignumbers.items(): for docname, fignumlist in self.env.toc_fignumbers.items():
for figtype, fignums in fignumlist.items(): for figtype, fignums in fignumlist.items():

View File

@@ -15,6 +15,7 @@ from typing import Any, Dict, Iterable, List, Tuple, Union
from docutils import nodes from docutils import nodes
from docutils.frontend import OptionParser from docutils.frontend import OptionParser
from docutils.io import FileOutput from docutils.io import FileOutput
from docutils.nodes import Node
from sphinx import addnodes, package_dir from sphinx import addnodes, package_dir
from sphinx.application import Sphinx from sphinx.application import Sphinx
@@ -154,7 +155,7 @@ class TexinfoBuilder(Builder):
for pendingnode in largetree.traverse(addnodes.pending_xref): for pendingnode in largetree.traverse(addnodes.pending_xref):
docname = pendingnode['refdocname'] docname = pendingnode['refdocname']
sectname = pendingnode['refsectname'] sectname = pendingnode['refsectname']
newnodes = [nodes.emphasis(sectname, sectname)] # type: List[nodes.Node] newnodes: List[Node] = [nodes.emphasis(sectname, sectname)]
for subdir, title in self.titles: for subdir, title in self.titles:
if docname.startswith(subdir): if docname.startswith(subdir):
newnodes.append(nodes.Text(_(' (in '), _(' (in '))) newnodes.append(nodes.Text(_(' (in '), _(' (in ')))

View File

@@ -33,11 +33,11 @@ class TextBuilder(Builder):
allow_parallel = True allow_parallel = True
default_translator_class = TextTranslator default_translator_class = TextTranslator
current_docname = None # type: str current_docname: str = None
def init(self) -> None: def init(self) -> None:
# section numbers for headings in the currently visited document # section numbers for headings in the currently visited document
self.secnumbers = {} # type: Dict[str, Tuple[int, ...]] self.secnumbers: Dict[str, Tuple[int, ...]] = {}
def get_outdated_docs(self) -> Iterator[str]: def get_outdated_docs(self) -> Iterator[str]:
for docname in self.env.found_docs: for docname in self.env.found_docs:

View File

@@ -37,7 +37,7 @@ class XMLBuilder(Builder):
out_suffix = '.xml' out_suffix = '.xml'
allow_parallel = True allow_parallel = True
_writer_class = XMLWriter # type: Union[Type[XMLWriter], Type[PseudoXMLWriter]] _writer_class: Union[Type[XMLWriter], Type[PseudoXMLWriter]] = XMLWriter
default_translator_class = XMLTranslator default_translator_class = XMLTranslator
def init(self) -> None: def init(self) -> None: