Skip to content

Commit 000ae2e

Browse files
committed
refactor: Use PEP-526 based variable annotation (sphinx.environment)
1 parent 6e4df0a commit 000ae2e

File tree

6 files changed

+79
-82
lines changed

6 files changed

+79
-82
lines changed

sphinx/environment/__init__.py

Lines changed: 63 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242

4343
logger = logging.getLogger(__name__)
4444

45-
default_settings = {
45+
default_settings: Dict[str, Any] = {
4646
'embed_stylesheet': False,
4747
'cloak_email_addresses': True,
4848
'pep_base_url': 'https://www.python.org/dev/peps/',
@@ -55,7 +55,7 @@
5555
'halt_level': 5,
5656
'file_insertion_enabled': True,
5757
'smartquotes_locales': [],
58-
} # type: Dict[str, Any]
58+
}
5959

6060
# This is increased every time an environment attribute is added
6161
# or changed to properly invalidate pickle files.
@@ -74,10 +74,10 @@
7474
}
7575

7676

77-
versioning_conditions = {
77+
versioning_conditions: Dict[str, Union[bool, Callable]] = {
7878
'none': False,
7979
'text': is_translatable,
80-
} # type: Dict[str, Union[bool, Callable]]
80+
}
8181

8282

8383
class BuildEnvironment:
@@ -87,24 +87,24 @@ class BuildEnvironment:
8787
transformations to resolve links to them.
8888
"""
8989

90-
domains = None # type: Dict[str, Domain]
90+
domains: Dict[str, Domain] = None
9191

9292
# --------- ENVIRONMENT INITIALIZATION -------------------------------------
9393

9494
def __init__(self, app: "Sphinx" = None):
95-
self.app = None # type: Sphinx
96-
self.doctreedir = None # type: str
97-
self.srcdir = None # type: str
98-
self.config = None # type: Config
99-
self.config_status = None # type: int
100-
self.config_status_extra = None # type: str
101-
self.events = None # type: EventManager
102-
self.project = None # type: Project
103-
self.version = None # type: Dict[str, str]
95+
self.app: Sphinx = None
96+
self.doctreedir: str = None
97+
self.srcdir: str = None
98+
self.config: Config = None
99+
self.config_status: int = None
100+
self.config_status_extra: str = None
101+
self.events: EventManager = None
102+
self.project: Project = None
103+
self.version: Dict[str, str] = None
104104

105105
# the method of doctree versioning; see set_versioning_method
106-
self.versioning_condition = None # type: Union[bool, Callable]
107-
self.versioning_compare = None # type: bool
106+
self.versioning_condition: Union[bool, Callable] = None
107+
self.versioning_compare: bool = None
108108

109109
# all the registered domains, set by the application
110110
self.domains = {}
@@ -116,70 +116,67 @@ def __init__(self, app: "Sphinx" = None):
116116
# All "docnames" here are /-separated and relative and exclude
117117
# the source suffix.
118118

119-
self.all_docs = {} # type: Dict[str, float]
120-
# docname -> mtime at the time of reading
121-
# contains all read docnames
122-
self.dependencies = defaultdict(set) # type: Dict[str, Set[str]]
123-
# docname -> set of dependent file
124-
# names, relative to documentation root
125-
self.included = defaultdict(set) # type: Dict[str, Set[str]]
126-
# docname -> set of included file
127-
# docnames included from other documents
128-
self.reread_always = set() # type: Set[str]
129-
# docnames to re-read unconditionally on
130-
# next build
119+
# docname -> mtime at the time of reading
120+
# contains all read docnames
121+
self.all_docs: Dict[str, float] = {}
122+
# docname -> set of dependent file
123+
# names, relative to documentation root
124+
self.dependencies: Dict[str, Set[str]] = defaultdict(set)
125+
# docname -> set of included file
126+
# docnames included from other documents
127+
self.included: Dict[str, Set[str]] = defaultdict(set)
128+
# docnames to re-read unconditionally on next build
129+
self.reread_always: Set[str] = set()
131130

132131
# File metadata
133-
self.metadata = defaultdict(dict) # type: Dict[str, Dict[str, Any]]
134-
# docname -> dict of metadata items
132+
# docname -> dict of metadata items
133+
self.metadata: Dict[str, Dict[str, Any]] = defaultdict(dict)
135134

136135
# TOC inventory
137-
self.titles = {} # type: Dict[str, nodes.title]
138-
# docname -> title node
139-
self.longtitles = {} # type: Dict[str, nodes.title]
140-
# docname -> title node; only different if
141-
# set differently with title directive
142-
self.tocs = {} # type: Dict[str, nodes.bullet_list]
143-
# docname -> table of contents nodetree
144-
self.toc_num_entries = {} # type: Dict[str, int]
145-
# docname -> number of real entries
136+
# docname -> title node
137+
self.titles: Dict[str, nodes.title] = {}
138+
# docname -> title node; only different if
139+
# set differently with title directive
140+
self.longtitles: Dict[str, nodes.title] = {}
141+
# docname -> table of contents nodetree
142+
self.tocs: Dict[str, nodes.bullet_list] = {}
143+
# docname -> number of real entries
144+
self.toc_num_entries: Dict[str, int] = {}
146145

147146
# used to determine when to show the TOC
148147
# in a sidebar (don't show if it's only one item)
149-
self.toc_secnumbers = {} # type: Dict[str, Dict[str, Tuple[int, ...]]]
150-
# docname -> dict of sectionid -> number
151-
self.toc_fignumbers = {} # type: Dict[str, Dict[str, Dict[str, Tuple[int, ...]]]]
152-
# docname -> dict of figtype ->
153-
# dict of figureid -> number
154-
155-
self.toctree_includes = {} # type: Dict[str, List[str]]
156-
# docname -> list of toctree includefiles
157-
self.files_to_rebuild = {} # type: Dict[str, Set[str]]
158-
# docname -> set of files
159-
# (containing its TOCs) to rebuild too
160-
self.glob_toctrees = set() # type: Set[str]
161-
# docnames that have :glob: toctrees
162-
self.numbered_toctrees = set() # type: Set[str]
163-
# docnames that have :numbered: toctrees
148+
# docname -> dict of sectionid -> number
149+
self.toc_secnumbers: Dict[str, Dict[str, Tuple[int, ...]]] = {}
150+
# docname -> dict of figtype -> dict of figureid -> number
151+
self.toc_fignumbers: Dict[str, Dict[str, Dict[str, Tuple[int, ...]]]] = {}
152+
153+
# docname -> list of toctree includefiles
154+
self.toctree_includes: Dict[str, List[str]] = {}
155+
# docname -> set of files (containing its TOCs) to rebuild too
156+
self.files_to_rebuild: Dict[str, Set[str]] = {}
157+
# docnames that have :glob: toctrees
158+
self.glob_toctrees: Set[str] = set()
159+
# docnames that have :numbered: toctrees
160+
self.numbered_toctrees: Set[str] = set()
164161

165162
# domain-specific inventories, here to be pickled
166-
self.domaindata = {} # type: Dict[str, Dict]
167-
# domainname -> domain-specific dict
163+
# domainname -> domain-specific dict
164+
self.domaindata: Dict[str, Dict] = {}
168165

169166
# these map absolute path -> (docnames, unique filename)
170-
self.images = FilenameUniqDict() # type: FilenameUniqDict
171-
self.dlfiles = DownloadFiles() # type: DownloadFiles
172-
# filename -> (set of docnames, destination)
167+
self.images: FilenameUniqDict = FilenameUniqDict()
168+
# filename -> (set of docnames, destination)
169+
self.dlfiles: DownloadFiles = DownloadFiles()
173170

174171
# the original URI for images
175-
self.original_image_uri = {} # type: Dict[str, str]
172+
self.original_image_uri: Dict[str, str] = {}
176173

177174
# temporary data storage while reading a document
178-
self.temp_data = {} # type: Dict[str, Any]
175+
self.temp_data: Dict[str, Any] = {}
179176
# context for cross-references (e.g. current module or class)
180177
# this is similar to temp_data, but will for example be copied to
181178
# attributes of "any" cross references
182-
self.ref_context = {} # type: Dict[str, Any]
179+
self.ref_context: Dict[str, Any] = {}
183180

184181
# set up environment
185182
if app:
@@ -269,7 +266,7 @@ def set_versioning_method(self, method: Union[str, Callable], compare: bool) ->
269266
raise an exception if the user tries to use an environment with an
270267
incompatible versioning method.
271268
"""
272-
condition = None # type: Union[bool, Callable]
269+
condition: Union[bool, Callable] = None
273270
if callable(method):
274271
condition = method
275272
else:
@@ -385,8 +382,8 @@ def get_outdated_files(self, config_changed: bool) -> Tuple[Set[str], Set[str],
385382
# clear all files no longer present
386383
removed = set(self.all_docs) - self.found_docs
387384

388-
added = set() # type: Set[str]
389-
changed = set() # type: Set[str]
385+
added: Set[str] = set()
386+
changed: Set[str] = set()
390387

391388
if config_changed:
392389
# config values affect e.g. substitutions
@@ -438,7 +435,7 @@ def get_outdated_files(self, config_changed: bool) -> Tuple[Set[str], Set[str],
438435
return added, changed, removed
439436

440437
def check_dependents(self, app: "Sphinx", already: Set[str]) -> Generator[str, None, None]:
441-
to_rewrite = [] # type: List[str]
438+
to_rewrite: List[str] = []
442439
for docnames in self.events.emit('env-get-updated', self):
443440
to_rewrite.extend(docnames)
444441
for docname in set(to_rewrite):

sphinx/environment/adapters/indexentries.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def create_index(self, builder: Builder, group_entries: bool = True,
3131
_fixre: Pattern = re.compile(r'(.*) ([(][^()]*[)])')
3232
) -> List[Tuple[str, List[Tuple[str, Any]]]]:
3333
"""Create the real index from the collected index entries."""
34-
new = {} # type: Dict[str, List]
34+
new: Dict[str, List] = {}
3535

3636
def add_entry(word: str, subword: str, main: str, link: bool = True,
3737
dic: Dict = new, key: str = None) -> None:
@@ -126,7 +126,7 @@ def keyfunc(entry: Tuple[str, List]) -> Tuple[Tuple[int, str], str]:
126126
# (in module foo)
127127
# (in module bar)
128128
oldkey = ''
129-
oldsubitems = None # type: Dict[str, List]
129+
oldsubitems: Dict[str, List] = None
130130
i = 0
131131
while i < len(newlist):
132132
key, (targets, subitems, _key) = newlist[i]

sphinx/environment/adapters/toctree.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def _toctree_add_classes(node: Element, depth: int) -> None:
102102
if not subnode['anchorname']:
103103
# give the whole branch a 'current' class
104104
# (useful for styling it differently)
105-
branchnode = subnode # type: Element
105+
branchnode: Element = subnode
106106
while branchnode:
107107
branchnode['classes'].append('current')
108108
branchnode = branchnode.parent
@@ -119,7 +119,7 @@ def _entries_from_toctree(toctreenode: addnodes.toctree, parents: List[str],
119119
) -> List[Element]:
120120
"""Return TOC entries for a toctree node."""
121121
refs = [(e[0], e[1]) for e in toctreenode['entries']]
122-
entries = [] # type: List[Element]
122+
entries: List[Element] = []
123123
for (title, ref) in refs:
124124
try:
125125
refdoc = None
@@ -268,7 +268,7 @@ def get_toctree_ancestors(self, docname: str) -> List[str]:
268268
for p, children in self.env.toctree_includes.items():
269269
for child in children:
270270
parent[child] = p
271-
ancestors = [] # type: List[str]
271+
ancestors: List[str] = []
272272
d = docname
273273
while d in parent and d not in ancestors:
274274
ancestors.append(d)
@@ -316,7 +316,7 @@ def get_toctree_for(self, docname: str, builder: "Builder", collapse: bool,
316316
**kwargs: Any) -> Element:
317317
"""Return the global TOC nodetree."""
318318
doctree = self.env.get_doctree(self.env.config.root_doc)
319-
toctrees = [] # type: List[Element]
319+
toctrees: List[Element] = []
320320
if 'includehidden' not in kwargs:
321321
kwargs['includehidden'] = True
322322
if 'maxdepth' not in kwargs or not kwargs['maxdepth']:

sphinx/environment/collectors/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class EnvironmentCollector:
2727
entries and toctrees, etc.
2828
"""
2929

30-
listener_ids = None # type: Dict[str, int]
30+
listener_ids: Dict[str, int] = None
3131

3232
def enable(self, app: "Sphinx") -> None:
3333
assert self.listener_ids is None

sphinx/environment/collectors/asset.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def process_doc(self, app: Sphinx, doctree: nodes.document) -> None:
4848
# choose the best image from these candidates. The special key * is
4949
# set if there is only single candidate to be used by a writer.
5050
# The special key ? is set for nonlocal URIs.
51-
candidates = {} # type: Dict[str, str]
51+
candidates: Dict[str, str] = {}
5252
node['candidates'] = candidates
5353
imguri = node['uri']
5454
if imguri.startswith('data:'):
@@ -94,7 +94,7 @@ def process_doc(self, app: Sphinx, doctree: nodes.document) -> None:
9494

9595
def collect_candidates(self, env: BuildEnvironment, imgpath: str,
9696
candidates: Dict[str, str], node: Node) -> None:
97-
globbed = {} # type: Dict[str, List[str]]
97+
globbed: Dict[str, List[str]] = {}
9898
for filename in glob(imgpath):
9999
new_imgpath = relative_path(path.join(env.srcdir, 'dummy'),
100100
filename)

sphinx/environment/collectors/toctree.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def process_doc(self, app: Sphinx, doctree: nodes.document) -> None:
6464

6565
def traverse_in_section(node: Element, cls: "Type[N]") -> List[N]:
6666
"""Like traverse(), but stay within the same section."""
67-
result = [] # type: List[N]
67+
result: List[N] = []
6868
if isinstance(node, cls):
6969
result.append(node)
7070
for child in node.children:
@@ -75,7 +75,7 @@ def traverse_in_section(node: Element, cls: "Type[N]") -> List[N]:
7575
return result
7676

7777
def build_toc(node: Element, depth: int = 1) -> nodes.bullet_list:
78-
entries = [] # type: List[Element]
78+
entries: List[Element] = []
7979
for sectionnode in node:
8080
# find all toctree nodes in this section and add them
8181
# to the toc (just copying the toctree node which is then
@@ -100,7 +100,7 @@ def build_toc(node: Element, depth: int = 1) -> nodes.bullet_list:
100100
'', '', internal=True, refuri=docname,
101101
anchorname=anchorname, *nodetext)
102102
para = addnodes.compact_paragraph('', '', reference)
103-
item = nodes.list_item('', para) # type: Element
103+
item: Element = nodes.list_item('', para)
104104
sub_item = build_toc(sectionnode, depth + 1)
105105
if sub_item:
106106
item += sub_item
@@ -136,7 +136,7 @@ def assign_section_numbers(self, env: BuildEnvironment) -> List[str]:
136136
# a list of all docnames whose section numbers changed
137137
rewrite_needed = []
138138

139-
assigned = set() # type: Set[str]
139+
assigned: Set[str] = set()
140140
old_secnumbers = env.toc_secnumbers
141141
env.toc_secnumbers = {}
142142

@@ -186,7 +186,7 @@ def _walk_toctree(toctreenode: addnodes.toctree, depth: int) -> None:
186186
'(nested numbered toctree?)'), ref,
187187
location=toctreenode, type='toc', subtype='secnum')
188188
elif ref in env.tocs:
189-
secnums = {} # type: Dict[str, Tuple[int, ...]]
189+
secnums: Dict[str, Tuple[int, ...]] = {}
190190
env.toc_secnumbers[ref] = secnums
191191
assigned.add(ref)
192192
_walk_toc(env.tocs[ref], secnums, depth, env.titles.get(ref))
@@ -210,10 +210,10 @@ def assign_figure_numbers(self, env: BuildEnvironment) -> List[str]:
210210

211211
rewrite_needed = []
212212

213-
assigned = set() # type: Set[str]
213+
assigned: Set[str] = set()
214214
old_fignumbers = env.toc_fignumbers
215215
env.toc_fignumbers = {}
216-
fignum_counter = {} # type: Dict[str, Dict[Tuple[int, ...], int]]
216+
fignum_counter: Dict[str, Dict[Tuple[int, ...], int]] = {}
217217

218218
def get_figtype(node: Node) -> str:
219219
for domain in env.domains.values():

0 commit comments

Comments
 (0)