Skip to content

Commit

Permalink
Merge pull request sphinx-doc#8984 from tk0miya/refactor_vartypes_wri…
Browse files Browse the repository at this point in the history
…ters

refactor: Use PEP-526 based variable annotation (sphinx.writers)
  • Loading branch information
tk0miya committed Mar 13, 2021
2 parents 2e43197 + dd24a4e commit c817c20
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 84 deletions.
6 changes: 3 additions & 3 deletions sphinx/writers/html.py
Expand Up @@ -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)
Expand Down Expand Up @@ -371,7 +371,7 @@ def visit_classifier(self, node: Element) -> None:
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>')
Expand All @@ -382,7 +382,7 @@ def visit_term(self, node: Element) -> None:

# 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.
Expand Down
6 changes: 3 additions & 3 deletions sphinx/writers/html5.py
Expand Up @@ -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)
Expand Down Expand Up @@ -322,7 +322,7 @@ def visit_classifier(self, node: Element) -> None:
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>')
Expand All @@ -333,7 +333,7 @@ def visit_term(self, node: Element) -> None:

# 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.
Expand Down
55 changes: 26 additions & 29 deletions sphinx/writers/latex.py
Expand Up @@ -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:
Expand All @@ -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."""
Expand Down Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -427,15 +425,15 @@ def __init__(self, document: nodes.document, builder: "LaTeXBuilder",

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)
Expand Down Expand Up @@ -1228,9 +1226,8 @@ def is_inline(self, node: Element) -> bool:
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:
Expand Down Expand Up @@ -1441,7 +1438,7 @@ def add_target(id: str) -> None:
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)

Expand Down
2 changes: 1 addition & 1 deletion sphinx/writers/manpage.py
Expand Up @@ -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)
Expand Down
54 changes: 24 additions & 30 deletions sphinx/writers/texinfo.py
Expand Up @@ -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')

Expand All @@ -146,7 +146,7 @@ def translate(self) -> None:

class TexinfoTranslator(SphinxTranslator):

builder = None # type: TexinfoBuilder
builder: "TexinfoBuilder" = None
ignore_missing_images = False

default_elements = {
Expand All @@ -168,40 +168,34 @@ def __init__(self, document: nodes.document, builder: "TexinfoBuilder") -> None:
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:
Expand Down Expand Up @@ -240,7 +234,7 @@ def init_settings(self) -> None:
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>'
Expand Down Expand Up @@ -299,7 +293,7 @@ def add_node_name(name: str) -> str:
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']
Expand Down Expand Up @@ -517,7 +511,7 @@ def footnotes_under(n: Element) -> Iterator[nodes.footnote]:
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()
Expand Down

0 comments on commit c817c20

Please sign in to comment.