Skip to content

Commit a504ac6

Browse files
authored
Improve static typing strictness (#10569)
1 parent a340427 commit a504ac6

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+223
-170
lines changed

sphinx/application.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -943,7 +943,7 @@ def add_post_transform(self, transform: Type[Transform]) -> None:
943943
"""
944944
self.registry.add_post_transform(transform)
945945

946-
def add_js_file(self, filename: str, priority: int = 500,
946+
def add_js_file(self, filename: Optional[str], priority: int = 500,
947947
loading_method: Optional[str] = None, **kwargs: Any) -> None:
948948
"""Register a JavaScript file to include in the HTML output.
949949

sphinx/builders/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,9 @@ def build_update(self) -> None:
301301
summary=__('targets for %d source files that are out of date') %
302302
len(to_build))
303303

304-
def build(self, docnames: Iterable[str], summary: str = None, method: str = 'update') -> None: # NOQA
304+
def build(
305+
self, docnames: Iterable[str], summary: Optional[str] = None, method: str = 'update'
306+
) -> None:
305307
"""Main build method.
306308
307309
First updates the environment, and then calls :meth:`write`.

sphinx/builders/_epub_base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import os
55
import re
66
from os import path
7-
from typing import Any, Dict, List, NamedTuple, Set, Tuple
7+
from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple
88
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
99

1010
from docutils import nodes
@@ -446,7 +446,7 @@ def copy_download_files(self) -> None:
446446
pass
447447

448448
def handle_page(self, pagename: str, addctx: Dict, templatename: str = 'page.html',
449-
outfilename: str = None, event_arg: Any = None) -> None:
449+
outfilename: Optional[str] = None, event_arg: Any = None) -> None:
450450
"""Create a rendered page.
451451
452452
This method is overwritten for genindex pages in order to fix href link

sphinx/builders/changes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def hl(no: int, line: str) -> str:
127127
with open(targetfn, 'w', encoding='utf-8') as f:
128128
text = ''.join(hl(i + 1, line) for (i, line) in enumerate(lines))
129129
ctx = {
130-
'filename': self.env.doc2path(docname, None),
130+
'filename': self.env.doc2path(docname, False),
131131
'text': text
132132
}
133133
f.write(self.templates.render('changes/rstsource.html', ctx))

sphinx/builders/dirhtml.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Directory HTML builders."""
22

33
from os import path
4-
from typing import Any, Dict
4+
from typing import Any, Dict, Optional
55

66
from sphinx.application import Sphinx
77
from sphinx.builders.html import StandaloneHTMLBuilder
@@ -19,7 +19,7 @@ class DirectoryHTMLBuilder(StandaloneHTMLBuilder):
1919
"""
2020
name = 'dirhtml'
2121

22-
def get_target_uri(self, docname: str, typ: str = None) -> str:
22+
def get_target_uri(self, docname: str, typ: Optional[str] = None) -> str:
2323
if docname == 'index':
2424
return ''
2525
if docname.endswith(SEP + 'index'):

sphinx/builders/dummy.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Do syntax checks, but no writing."""
22

3-
from typing import Any, Dict, Set
3+
from typing import Any, Dict, Optional, Set
44

55
from docutils.nodes import Node
66

@@ -21,7 +21,7 @@ def init(self) -> None:
2121
def get_outdated_docs(self) -> Set[str]:
2222
return self.env.found_docs
2323

24-
def get_target_uri(self, docname: str, typ: str = None) -> str:
24+
def get_target_uri(self, docname: str, typ: Optional[str] = None) -> str:
2525
return ''
2626

2727
def prepare_writing(self, docnames: Set[str]) -> None:

sphinx/builders/epub3.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def handle_finish(self) -> None:
7777
self.build_toc()
7878
self.build_epub()
7979

80-
def content_metadata(self) -> Dict:
80+
def content_metadata(self) -> Dict[str, Any]:
8181
"""Create a dictionary with all metadata for the content.opf
8282
file properly escaped.
8383
"""
@@ -144,11 +144,11 @@ def build_navlist(self, navnodes: List[Dict[str, Any]]) -> List[NavPoint]:
144144

145145
return navstack[0].children
146146

147-
def navigation_doc_metadata(self, navlist: List[NavPoint]) -> Dict:
147+
def navigation_doc_metadata(self, navlist: List[NavPoint]) -> Dict[str, Any]:
148148
"""Create a dictionary with all metadata for the nav.xhtml file
149149
properly escaped.
150150
"""
151-
metadata: Dict = {}
151+
metadata = {}
152152
metadata['lang'] = html.escape(self.config.epub_language)
153153
metadata['toc_locale'] = html.escape(self.guide_titles['toc'])
154154
metadata['navlist'] = navlist
@@ -217,7 +217,7 @@ def validate_config_values(app: Sphinx) -> None:
217217

218218
def convert_epub_css_files(app: Sphinx, config: Config) -> None:
219219
"""This converts string styled epub_css_files to tuple styled one."""
220-
epub_css_files: List[Tuple[str, Dict]] = []
220+
epub_css_files: List[Tuple[str, Dict[str, Any]]] = []
221221
for entry in config.epub_css_files:
222222
if isinstance(entry, str):
223223
epub_css_files.append((entry, {}))
@@ -236,7 +236,7 @@ def setup(app: Sphinx) -> Dict[str, Any]:
236236
app.add_builder(Epub3Builder)
237237

238238
# config values
239-
app.add_config_value('epub_basename', lambda self: make_filename(self.project), None)
239+
app.add_config_value('epub_basename', lambda self: make_filename(self.project), False)
240240
app.add_config_value('epub_version', 3.0, 'epub') # experimental
241241
app.add_config_value('epub_theme', 'epub', 'epub')
242242
app.add_config_value('epub_theme_options', {}, 'epub')

sphinx/builders/gettext.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
from datetime import datetime, timedelta, tzinfo
66
from os import getenv, path, walk
77
from time import time
8-
from typing import Any, DefaultDict, Dict, Generator, Iterable, List, Set, Tuple, Union
8+
from typing import (Any, DefaultDict, Dict, Generator, Iterable, List, Optional, Set, Tuple,
9+
Union)
910
from uuid import uuid4
1011

1112
from docutils import nodes
@@ -78,7 +79,9 @@ def __init__(self, source: str, line: int) -> None:
7879

7980

8081
class GettextRenderer(SphinxRenderer):
81-
def __init__(self, template_path: str = None, outdir: str = None) -> None:
82+
def __init__(
83+
self, template_path: Optional[str] = None, outdir: Optional[str] = None
84+
) -> None:
8285
self.outdir = outdir
8386
if template_path is None:
8487
template_path = path.join(package_dir, 'templates', 'gettext')
@@ -93,7 +96,7 @@ def escape(s: str) -> str:
9396
self.env.filters['e'] = escape
9497
self.env.filters['escape'] = escape
9598

96-
def render(self, filename: str, context: Dict) -> str:
99+
def render(self, filename: str, context: Dict[str, Any]) -> str:
97100
def _relpath(s: str) -> str:
98101
return canon_path(relpath(s, self.outdir))
99102

@@ -127,7 +130,7 @@ def init(self) -> None:
127130
self.tags = I18nTags()
128131
self.catalogs: DefaultDict[str, Catalog] = defaultdict(Catalog)
129132

130-
def get_target_uri(self, docname: str, typ: str = None) -> str:
133+
def get_target_uri(self, docname: str, typ: Optional[str] = None) -> str:
131134
return ''
132135

133136
def get_outdated_docs(self) -> Set[str]:
@@ -179,10 +182,10 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
179182
super().__init__(*args, **kwargs)
180183
self.tzdelta = tzdelta
181184

182-
def utcoffset(self, dt: datetime) -> timedelta:
185+
def utcoffset(self, dt: Optional[datetime]) -> timedelta:
183186
return self.tzdelta
184187

185-
def dst(self, dt: datetime) -> timedelta:
188+
def dst(self, dt: Optional[datetime]) -> timedelta:
186189
return timedelta(0)
187190

188191

@@ -249,7 +252,9 @@ def _extract_from_template(self) -> None:
249252
except Exception as exc:
250253
raise ThemeError('%s: %r' % (template, exc)) from exc
251254

252-
def build(self, docnames: Iterable[str], summary: str = None, method: str = 'update') -> None: # NOQA
255+
def build(
256+
self, docnames: Iterable[str], summary: Optional[str] = None, method: str = 'update'
257+
) -> None:
253258
self._extract_from_template()
254259
super().build(docnames, summary, method)
255260

sphinx/builders/html/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -823,7 +823,7 @@ def copy_stemmer_js(self) -> None:
823823
if jsfile:
824824
copyfile(jsfile, path.join(self.outdir, '_static', '_stemmer.js'))
825825

826-
def copy_theme_static_files(self, context: Dict) -> None:
826+
def copy_theme_static_files(self, context: Dict[str, Any]) -> None:
827827
def onerror(filename: str, error: Exception) -> None:
828828
logger.warning(__('Failed to copy a file in html_static_file: %s: %r'),
829829
filename, error)

sphinx/builders/linkcheck.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import re
55
import socket
66
import time
7+
from copy import deepcopy
78
from datetime import datetime, timezone
89
from email.utils import parsedate_to_datetime
910
from html.parser import HTMLParser
@@ -117,7 +118,7 @@ def init(self) -> None:
117118
socket.setdefaulttimeout(5.0)
118119

119120
def process_result(self, result: CheckResult) -> None:
120-
filename = self.env.doc2path(result.docname, None)
121+
filename = self.env.doc2path(result.docname, False)
121122

122123
linkstat = {"filename": filename, "lineno": result.lineno,
123124
"status": result.status, "code": result.code, "uri": result.uri,
@@ -202,7 +203,7 @@ def __init__(self, env: BuildEnvironment, config: Config) -> None:
202203
self.rate_limits: Dict[str, RateLimit] = {}
203204
self.rqueue: Queue = Queue()
204205
self.workers: List[Thread] = []
205-
self.wqueue: PriorityQueue = PriorityQueue()
206+
self.wqueue: PriorityQueue[CheckRequest] = PriorityQueue()
206207

207208
self.to_ignore = [re.compile(x) for x in self.config.linkcheck_ignore]
208209

@@ -267,7 +268,7 @@ def run(self) -> None:
267268
if self.config.linkcheck_timeout:
268269
kwargs['timeout'] = self.config.linkcheck_timeout
269270

270-
def get_request_headers() -> Dict:
271+
def get_request_headers() -> Dict[str, str]:
271272
url = urlparse(uri)
272273
candidates = ["%s://%s" % (url.scheme, url.netloc),
273274
"%s://%s/" % (url.scheme, url.netloc),
@@ -276,7 +277,7 @@ def get_request_headers() -> Dict:
276277

277278
for u in candidates:
278279
if u in self.config.linkcheck_request_headers:
279-
headers = dict(DEFAULT_REQUEST_HEADERS)
280+
headers = deepcopy(DEFAULT_REQUEST_HEADERS)
280281
headers.update(self.config.linkcheck_request_headers[u])
281282
return headers
282283

@@ -561,19 +562,19 @@ def setup(app: Sphinx) -> Dict[str, Any]:
561562
app.add_builder(CheckExternalLinksBuilder)
562563
app.add_post_transform(HyperlinkCollector)
563564

564-
app.add_config_value('linkcheck_ignore', [], None)
565-
app.add_config_value('linkcheck_exclude_documents', [], None)
566-
app.add_config_value('linkcheck_allowed_redirects', {}, None)
567-
app.add_config_value('linkcheck_auth', [], None)
568-
app.add_config_value('linkcheck_request_headers', {}, None)
569-
app.add_config_value('linkcheck_retries', 1, None)
570-
app.add_config_value('linkcheck_timeout', None, None, [int])
571-
app.add_config_value('linkcheck_workers', 5, None)
572-
app.add_config_value('linkcheck_anchors', True, None)
565+
app.add_config_value('linkcheck_ignore', [], False)
566+
app.add_config_value('linkcheck_exclude_documents', [], False)
567+
app.add_config_value('linkcheck_allowed_redirects', {}, False)
568+
app.add_config_value('linkcheck_auth', [], False)
569+
app.add_config_value('linkcheck_request_headers', {}, False)
570+
app.add_config_value('linkcheck_retries', 1, False)
571+
app.add_config_value('linkcheck_timeout', None, False, [int])
572+
app.add_config_value('linkcheck_workers', 5, False)
573+
app.add_config_value('linkcheck_anchors', True, False)
573574
# Anchors starting with ! are ignored since they are
574575
# commonly used for dynamic pages
575-
app.add_config_value('linkcheck_anchors_ignore', ["^!"], None)
576-
app.add_config_value('linkcheck_rate_limit_timeout', 300.0, None)
576+
app.add_config_value('linkcheck_anchors_ignore', ["^!"], False)
577+
app.add_config_value('linkcheck_rate_limit_timeout', 300.0, False)
577578

578579
app.add_event('linkcheck-process-uri')
579580

sphinx/builders/manpage.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import warnings
44
from os import path
5-
from typing import Any, Dict, List, Set, Tuple, Union
5+
from typing import Any, Dict, List, Optional, Set, Tuple, Union
66

77
from docutils.frontend import OptionParser
88
from docutils.io import FileOutput
@@ -40,7 +40,7 @@ def init(self) -> None:
4040
def get_outdated_docs(self) -> Union[str, List[str]]:
4141
return 'all manpages' # for now
4242

43-
def get_target_uri(self, docname: str, typ: str = None) -> str:
43+
def get_target_uri(self, docname: str, typ: Optional[str] = None) -> str:
4444
return ''
4545

4646
@progress_message(__('writing'))
@@ -111,9 +111,9 @@ def default_man_pages(config: Config) -> List[Tuple[str, str, str, List[str], in
111111
def setup(app: Sphinx) -> Dict[str, Any]:
112112
app.add_builder(ManualPageBuilder)
113113

114-
app.add_config_value('man_pages', default_man_pages, None)
115-
app.add_config_value('man_show_urls', False, None)
116-
app.add_config_value('man_make_section_directory', False, None)
114+
app.add_config_value('man_pages', default_man_pages, False)
115+
app.add_config_value('man_show_urls', False, False)
116+
app.add_config_value('man_make_section_directory', False, False)
117117

118118
return {
119119
'version': 'builtin',

sphinx/builders/singlehtml.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Single HTML builders."""
22

33
from os import path
4-
from typing import Any, Dict, List, Tuple, Union
4+
from typing import Any, Dict, List, Optional, Tuple, Union
55

66
from docutils import nodes
77
from docutils.nodes import Node
@@ -27,10 +27,10 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder):
2727

2828
copysource = False
2929

30-
def get_outdated_docs(self) -> Union[str, List[str]]: # type: ignore
30+
def get_outdated_docs(self) -> Union[str, List[str]]: # type: ignore[override]
3131
return 'all documents'
3232

33-
def get_target_uri(self, docname: str, typ: str = None) -> str:
33+
def get_target_uri(self, docname: str, typ: Optional[str] = None) -> str:
3434
if docname in self.env.all_docs:
3535
# all references are on the same page...
3636
return self.config.root_doc + self.out_suffix + \
@@ -39,7 +39,7 @@ def get_target_uri(self, docname: str, typ: str = None) -> str:
3939
# chances are this is a html_additional_page
4040
return docname + self.out_suffix
4141

42-
def get_relative_uri(self, from_: str, to: str, typ: str = None) -> str:
42+
def get_relative_uri(self, from_: str, to: str, typ: Optional[str] = None) -> str:
4343
# ignore source
4444
return self.get_target_uri(to, typ)
4545

@@ -113,7 +113,7 @@ def assemble_toc_fignumbers(self) -> Dict[str, Dict[str, Dict[str, Tuple[int, ..
113113

114114
return {self.config.root_doc: new_fignumbers}
115115

116-
def get_doc_context(self, docname: str, body: str, metatags: str) -> Dict:
116+
def get_doc_context(self, docname: str, body: str, metatags: str) -> Dict[str, Any]:
117117
# no relation links...
118118
toctree = TocTree(self.env).get_toctree_for(self.config.root_doc, self, False)
119119
# if there is no toctree, toc is None

sphinx/builders/texinfo.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import os
44
import warnings
55
from os import path
6-
from typing import Any, Dict, Iterable, List, Tuple, Union
6+
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
77

88
from docutils import nodes
99
from docutils.frontend import OptionParser
@@ -52,13 +52,13 @@ def init(self) -> None:
5252
def get_outdated_docs(self) -> Union[str, List[str]]:
5353
return 'all documents' # for now
5454

55-
def get_target_uri(self, docname: str, typ: str = None) -> str:
55+
def get_target_uri(self, docname: str, typ: Optional[str] = None) -> str:
5656
if docname not in self.docnames:
5757
raise NoUri(docname, typ)
5858
else:
5959
return '%' + docname
6060

61-
def get_relative_uri(self, from_: str, to: str, typ: str = None) -> str:
61+
def get_relative_uri(self, from_: str, to: str, typ: Optional[str] = None) -> str:
6262
# ignore source path
6363
return self.get_target_uri(to, typ)
6464

@@ -202,13 +202,13 @@ def default_texinfo_documents(config: Config) -> List[Tuple[str, str, str, str,
202202
def setup(app: Sphinx) -> Dict[str, Any]:
203203
app.add_builder(TexinfoBuilder)
204204

205-
app.add_config_value('texinfo_documents', default_texinfo_documents, None)
206-
app.add_config_value('texinfo_appendices', [], None)
207-
app.add_config_value('texinfo_elements', {}, None)
208-
app.add_config_value('texinfo_domain_indices', True, None, [list])
209-
app.add_config_value('texinfo_show_urls', 'footnote', None)
210-
app.add_config_value('texinfo_no_detailmenu', False, None)
211-
app.add_config_value('texinfo_cross_references', True, None)
205+
app.add_config_value('texinfo_documents', default_texinfo_documents, False)
206+
app.add_config_value('texinfo_appendices', [], False)
207+
app.add_config_value('texinfo_elements', {}, False)
208+
app.add_config_value('texinfo_domain_indices', True, False, [list])
209+
app.add_config_value('texinfo_show_urls', 'footnote', False)
210+
app.add_config_value('texinfo_no_detailmenu', False, False)
211+
app.add_config_value('texinfo_cross_references', True, False)
212212

213213
return {
214214
'version': 'builtin',

0 commit comments

Comments
 (0)