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

This commit is contained in:
Takeshi KOMIYA 2021-03-12 01:55:01 +09:00
parent 4bb151bf36
commit dd24a4ef2d
6 changed files with 74 additions and 84 deletions

View File

@ -83,7 +83,7 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
Our custom HTML translator.
"""
builder = None # type: StandaloneHTMLBuilder
builder: "StandaloneHTMLBuilder" = None
def __init__(self, document: nodes.document, builder: Builder) -> None:
super().__init__(document, builder)
@ -371,7 +371,7 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
def depart_classifier(self, node: Element) -> None:
self.body.append('</span>')
next_node = node.next_node(descend=False, siblings=True) # type: Node
next_node: Node = node.next_node(descend=False, siblings=True)
if not isinstance(next_node, nodes.classifier):
# close `<dt>` tag at the tail of classifiers
self.body.append('</dt>')
@ -382,7 +382,7 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
# overwritten
def depart_term(self, node: Element) -> None:
next_node = node.next_node(descend=False, siblings=True) # type: Node
next_node: Node = node.next_node(descend=False, siblings=True)
if isinstance(next_node, nodes.classifier):
# Leave the end tag to `self.depart_classifier()`, in case
# there's a classifier.

View File

@ -54,7 +54,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
Our custom HTML translator.
"""
builder = None # type: StandaloneHTMLBuilder
builder: "StandaloneHTMLBuilder" = None
def __init__(self, document: nodes.document, builder: Builder) -> None:
super().__init__(document, builder)
@ -322,7 +322,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
def depart_classifier(self, node: Element) -> None:
self.body.append('</span>')
next_node = node.next_node(descend=False, siblings=True) # type: Node
next_node: Node = node.next_node(descend=False, siblings=True)
if not isinstance(next_node, nodes.classifier):
# close `<dt>` tag at the tail of classifiers
self.body.append('</dt>')
@ -333,7 +333,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
# overwritten
def depart_term(self, node: Element) -> None:
next_node = node.next_node(descend=False, siblings=True) # type: Node
next_node: Node = node.next_node(descend=False, siblings=True)
if isinstance(next_node, nodes.classifier):
# Leave the end tag to `self.depart_classifier()`, in case
# there's a classifier.

View File

@ -79,14 +79,14 @@ class LaTeXWriter(writers.Writer):
('Document class', ['--docclass'], {'default': 'manual'}),
('Author', ['--author'], {'default': ''}),
))
settings_defaults = {} # type: Dict
settings_defaults: Dict = {}
output = None
def __init__(self, builder: "LaTeXBuilder") -> None:
super().__init__()
self.builder = builder
self.theme = None # type: Theme
self.theme: Theme = None
def translate(self) -> None:
try:
@ -106,28 +106,26 @@ class Table:
"""A table data"""
def __init__(self, node: Element) -> None:
self.header = [] # type: List[str]
self.body = [] # type: List[str]
self.header: List[str] = []
self.body: List[str] = []
self.align = node.get('align', 'default')
self.classes: List[str] = node.get('classes', [])
self.colcount = 0
self.colspec = None # type: str
self.colwidths = [] # type: List[int]
self.colspec: str = None
self.colwidths: List[int] = []
self.has_problematic = False
self.has_oldproblematic = False
self.has_verbatim = False
self.caption = None # type: List[str]
self.stubs = [] # type: List[int]
self.caption: List[str] = None
self.stubs: List[int] = []
# current position
self.col = 0
self.row = 0
# for internal use
self.classes = node.get('classes', []) # type: List[str]
self.cells = defaultdict(int) # type: Dict[Tuple[int, int], int]
# it maps table location to cell_id
# (cell = rectangular area)
self.cell_id = 0 # last assigned cell_id
# A mapping a table location to the cell_id (cell = rectangular area)
self.cells: Dict[Tuple[int, int], int] = defaultdict(int)
self.cell_id = 0 # last assigned cell_id
def is_longtable(self) -> bool:
"""True if and only if table uses longtable environment."""
@ -272,7 +270,7 @@ def rstdim_to_latexdim(width_str: str, scale: int = 100) -> str:
class LaTeXTranslator(SphinxTranslator):
builder = None # type: LaTeXBuilder
builder: "LaTeXBuilder" = None
secnumdepth = 2 # legacy sphinxhowto.cls uses this, whereas article.cls
# default is originally 3. For book/report, 2 is already LaTeX default.
@ -284,7 +282,7 @@ class LaTeXTranslator(SphinxTranslator):
def __init__(self, document: nodes.document, builder: "LaTeXBuilder",
theme: "Theme" = None) -> None:
super().__init__(document, builder)
self.body = [] # type: List[str]
self.body: List[str] = []
self.theme = theme
if theme is None:
@ -427,15 +425,15 @@ class LaTeXTranslator(SphinxTranslator):
self.highlighter = highlighting.PygmentsBridge('latex', self.config.pygments_style,
latex_engine=self.config.latex_engine)
self.context = [] # type: List[Any]
self.descstack = [] # type: List[str]
self.tables = [] # type: List[Table]
self.next_table_colspec = None # type: str
self.bodystack = [] # type: List[List[str]]
self.footnote_restricted = None # type: nodes.Element
self.pending_footnotes = [] # type: List[nodes.footnote_reference]
self.curfilestack = [] # type: List[str]
self.handled_abbrs = set() # type: Set[str]
self.context: List[Any] = []
self.descstack: List[str] = []
self.tables: List[Table] = []
self.next_table_colspec: str = None
self.bodystack: List[List[str]] = []
self.footnote_restricted: Element = None
self.pending_footnotes: List[nodes.footnote_reference] = []
self.curfilestack: List[str] = []
self.handled_abbrs: Set[str] = set()
def pushbody(self, newbody: List[str]) -> None:
self.bodystack.append(self.body)
@ -1228,9 +1226,8 @@ class LaTeXTranslator(SphinxTranslator):
return isinstance(node.parent, nodes.TextElement)
def visit_image(self, node: Element) -> None:
pre = [] # type: List[str]
# in reverse order
post = [] # type: List[str]
pre: List[str] = [] # in reverse order
post: List[str] = []
include_graphics_options = []
has_hyperlink = isinstance(node.parent, nodes.reference)
if has_hyperlink:
@ -1441,7 +1438,7 @@ class LaTeXTranslator(SphinxTranslator):
self.body.append(self.hypertarget(id, anchor=anchor))
# skip if visitor for next node supports hyperlink
next_node = node # type: nodes.Node
next_node: Node = node
while isinstance(next_node, nodes.target):
next_node = next_node.next_node(ascend=True)

View File

@ -73,7 +73,7 @@ class ManualPageTranslator(SphinxTranslator, BaseTranslator):
Custom translator.
"""
_docinfo = {} # type: Dict[str, Any]
_docinfo: Dict[str, Any] = {}
def __init__(self, document: nodes.document, builder: Builder) -> None:
super().__init__(document, builder)

View File

@ -117,17 +117,17 @@ class TexinfoWriter(writers.Writer):
"""Texinfo writer for generating Texinfo documents."""
supported = ('texinfo', 'texi')
settings_spec = (
settings_spec: Tuple[str, Any, Tuple[Tuple[str, List[str], Dict[str, str]], ...]] = (
'Texinfo Specific Options', None, (
("Name of the Info file", ['--texinfo-filename'], {'default': ''}),
('Dir entry', ['--texinfo-dir-entry'], {'default': ''}),
('Description', ['--texinfo-dir-description'], {'default': ''}),
('Category', ['--texinfo-dir-category'], {'default':
'Miscellaneous'}))) # type: Tuple[str, Any, Tuple[Tuple[str, List[str], Dict[str, str]], ...]] # NOQA
'Miscellaneous'})))
settings_defaults = {} # type: Dict
settings_defaults: Dict = {}
output = None # type: str
output: str = None
visitor_attributes = ('output', 'fragment')
@ -146,7 +146,7 @@ class TexinfoWriter(writers.Writer):
class TexinfoTranslator(SphinxTranslator):
builder = None # type: TexinfoBuilder
builder: "TexinfoBuilder" = None
ignore_missing_images = False
default_elements = {
@ -168,40 +168,34 @@ class TexinfoTranslator(SphinxTranslator):
super().__init__(document, builder)
self.init_settings()
self.written_ids = set() # type: Set[str]
# node names and anchors in output
self.written_ids: Set[str] = set() # node names and anchors in output
# node names and anchors that should be in output
self.referenced_ids = set() # type: Set[str]
self.indices = [] # type: List[Tuple[str, str]]
# (node name, content)
self.short_ids = {} # type: Dict[str, str]
# anchors --> short ids
self.node_names = {} # type: Dict[str, str]
# node name --> node's name to display
self.node_menus = {} # type: Dict[str, List[str]]
# node name --> node's menu entries
self.rellinks = {} # type: Dict[str, List[str]]
# node name --> (next, previous, up)
self.referenced_ids: Set[str] = set()
self.indices: List[Tuple[str, str]] = [] # (node name, content)
self.short_ids: Dict[str, str] = {} # anchors --> short ids
self.node_names: Dict[str, str] = {} # node name --> node's name to display
self.node_menus: Dict[str, List[str]] = {} # node name --> node's menu entries
self.rellinks: Dict[str, List[str]] = {} # node name --> (next, previous, up)
self.collect_indices()
self.collect_node_names()
self.collect_node_menus()
self.collect_rellinks()
self.body = [] # type: List[str]
self.context = [] # type: List[str]
self.descs = [] # type: List[addnodes.desc]
self.previous_section = None # type: nodes.section
self.body: List[str] = []
self.context: List[str] = []
self.descs: List[addnodes.desc] = []
self.previous_section: nodes.section = None
self.section_level = 0
self.seen_title = False
self.next_section_ids = set() # type: Set[str]
self.next_section_ids: Set[str] = set()
self.escape_newlines = 0
self.escape_hyphens = 0
self.curfilestack = [] # type: List[str]
self.footnotestack = [] # type: List[Dict[str, List[Union[collected_footnote, bool]]]] # NOQA
self.curfilestack: List[str] = []
self.footnotestack: List[Dict[str, List[Union[collected_footnote, bool]]]] = [] # NOQA
self.in_footnote = 0
self.handled_abbrs = set() # type: Set[str]
self.colwidths = None # type: List[int]
self.handled_abbrs: Set[str] = set()
self.colwidths: List[int] = None
def finish(self) -> None:
if self.previous_section is None:
@ -240,7 +234,7 @@ class TexinfoTranslator(SphinxTranslator):
language=self.config.language))
})
# title
title = self.settings.title # type: str
title: str = self.settings.title
if not title:
title_node = self.document.next_node(nodes.title)
title = title_node.astext() if title_node else '<untitled>'
@ -299,7 +293,7 @@ class TexinfoTranslator(SphinxTranslator):
def collect_node_menus(self) -> None:
"""Collect the menu entries for each "node" section."""
node_menus = self.node_menus
targets = [self.document] # type: List[Element]
targets: List[Element] = [self.document]
targets.extend(self.document.traverse(nodes.section))
for node in targets:
assert 'node_name' in node and node['node_name']
@ -517,7 +511,7 @@ class TexinfoTranslator(SphinxTranslator):
continue
elif isinstance(c, nodes.Element):
yield from footnotes_under(c)
fnotes = {} # type: Dict[str, List[Union[collected_footnote, bool]]]
fnotes: Dict[str, List[Union[collected_footnote, bool]]] = {}
for fn in footnotes_under(node):
label = cast(nodes.label, fn[0])
num = label.astext().strip()

View File

@ -33,11 +33,11 @@ class Cell:
"""
def __init__(self, text: str = "", rowspan: int = 1, colspan: int = 1) -> None:
self.text = text
self.wrapped = [] # type: List[str]
self.wrapped: List[str] = []
self.rowspan = rowspan
self.colspan = colspan
self.col = None # type: Optional[int]
self.row = None # type: Optional[int]
self.col: Optional[int] = None
self.row: Optional[int] = None
def __repr__(self) -> str:
return "<Cell {!r} {}v{}/{}>{}>".format(
@ -98,10 +98,9 @@ class Table:
"""
def __init__(self, colwidth: List[int] = None) -> None:
self.lines = [] # type: List[List[Cell]]
self.lines: List[List[Cell]] = []
self.separator = 0
self.colwidth = (colwidth if colwidth is not None
else []) # type: List[int]
self.colwidth: List[int] = (colwidth if colwidth is not None else [])
self.current_line = 0
self.current_col = 0
@ -168,7 +167,7 @@ class Table:
@property
def cells(self) -> Generator[Cell, None, None]:
seen = set() # type: Set[Cell]
seen: Set[Cell] = set()
for lineno, line in enumerate(self.lines):
for colno, cell in enumerate(line):
if cell and cell not in seen:
@ -205,7 +204,7 @@ class Table:
"""Called on the line *before* lineno.
Called with no *lineno* for the last sep.
"""
out = [] # type: List[str]
out: List[str] = []
for colno, width in enumerate(self.measured_widths):
if (
lineno is not None and
@ -267,7 +266,7 @@ class TextWrapper(textwrap.TextWrapper):
The original _wrap_chunks uses len() to calculate width.
This method respects wide/fullwidth characters for width adjustment.
"""
lines = [] # type: List[str]
lines: List[str] = []
if self.width <= 0:
raise ValueError("invalid width %r (must be > 0)" % self.width)
@ -328,7 +327,7 @@ class TextWrapper(textwrap.TextWrapper):
"""
def split(t: str) -> List[str]:
return super(TextWrapper, self)._split(t)
chunks = [] # type: List[str]
chunks: List[str] = []
for chunk in split(text):
for w, g in groupby(chunk, column_width):
if w == 1:
@ -367,9 +366,9 @@ def my_wrap(text: str, width: int = MAXWIDTH, **kwargs: Any) -> List[str]:
class TextWriter(writers.Writer):
supported = ('text',)
settings_spec = ('No options here.', '', ())
settings_defaults = {} # type: Dict
settings_defaults: Dict = {}
output = None # type: str
output: str = None
def __init__(self, builder: "TextBuilder") -> None:
super().__init__()
@ -382,7 +381,7 @@ class TextWriter(writers.Writer):
class TextTranslator(SphinxTranslator):
builder = None # type: TextBuilder
builder: "TextBuilder" = None
def __init__(self, document: nodes.document, builder: "TextBuilder") -> None:
super().__init__(document, builder)
@ -397,12 +396,12 @@ class TextTranslator(SphinxTranslator):
self.sectionchars = self.config.text_sectionchars
self.add_secnumbers = self.config.text_add_secnumbers
self.secnumber_suffix = self.config.text_secnumber_suffix
self.states = [[]] # type: List[List[Tuple[int, Union[str, List[str]]]]]
self.states: List[List[Tuple[int, Union[str, List[str]]]]] = [[]]
self.stateindent = [0]
self.list_counter = [] # type: List[int]
self.list_counter: List[int] = []
self.sectionlevel = 0
self.lineblocklevel = 0
self.table = None # type: Table
self.table: Table = None
def add_text(self, text: str) -> None:
self.states[-1].append((-1, text))
@ -415,8 +414,8 @@ class TextTranslator(SphinxTranslator):
content = self.states.pop()
maxindent = sum(self.stateindent)
indent = self.stateindent.pop()
result = [] # type: List[Tuple[int, List[str]]]
toformat = [] # type: List[str]
result: List[Tuple[int, List[str]]] = []
toformat: List[str] = []
def do_format() -> None:
if not toformat: