Skip to content

Commit 43434a0

Browse files
authored
Merge pull request #9164 from tk0miya/refactor_Optional
refactor: Add Optional to type annotations
2 parents f31af4b + 930bf6c commit 43434a0

File tree

10 files changed

+30
-27
lines changed

10 files changed

+30
-27
lines changed

sphinx/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ def __setstate__(self, state: Dict) -> None:
309309
self.__dict__.update(state)
310310

311311

312-
def eval_config_file(filename: str, tags: Tags) -> Dict[str, Any]:
312+
def eval_config_file(filename: str, tags: Optional[Tags]) -> Dict[str, Any]:
313313
"""Evaluate a config file."""
314314
namespace: Dict[str, Any] = {}
315315
namespace['__file__'] = filename

sphinx/environment/adapters/toctree.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
:license: BSD, see LICENSE for details.
99
"""
1010

11-
from typing import TYPE_CHECKING, Any, Iterable, List, cast
11+
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, cast
1212

1313
from docutils import nodes
1414
from docutils.nodes import Element, Node
@@ -48,7 +48,7 @@ def note(self, docname: str, toctreenode: addnodes.toctree) -> None:
4848

4949
def resolve(self, docname: str, builder: "Builder", toctree: addnodes.toctree,
5050
prune: bool = True, maxdepth: int = 0, titles_only: bool = False,
51-
collapse: bool = False, includehidden: bool = False) -> Element:
51+
collapse: bool = False, includehidden: bool = False) -> Optional[Element]:
5252
"""Resolve a *toctree* node into individual bullet lists with titles
5353
as items, returning None (if no containing titles are found) or
5454
a new node.

sphinx/project.py

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

1111
import os
1212
from glob import glob
13-
from typing import Dict, List, Set
13+
from typing import Dict, List, Optional, Set
1414

1515
from sphinx.locale import __
1616
from sphinx.util import get_matching_files, logging, path_stabilize
@@ -60,7 +60,7 @@ def discover(self, exclude_paths: List[str] = []) -> Set[str]:
6060

6161
return self.docnames
6262

63-
def path2doc(self, filename: str) -> str:
63+
def path2doc(self, filename: str) -> Optional[str]:
6464
"""Return the docname for the filename if the file is document.
6565
6666
*filename* should be absolute or relative to the source directory.

sphinx/transforms/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
import re
1212
import warnings
13-
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Tuple
13+
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Tuple
1414

1515
from docutils import nodes
1616
from docutils.nodes import Element, Node, Text
@@ -72,8 +72,8 @@ class SphinxTransformer(Transformer):
7272
A transformer for Sphinx.
7373
"""
7474

75-
document: nodes.document = None
76-
env: "BuildEnvironment" = None
75+
document: nodes.document
76+
env: Optional["BuildEnvironment"] = None
7777

7878
def set_environment(self, env: "BuildEnvironment") -> None:
7979
self.env = env

sphinx/util/docfields.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ class DocFieldTransformer:
209209
Transforms field lists in "doc field" syntax into better-looking
210210
equivalents, using the field type definitions given on a domain.
211211
"""
212-
typemap: Dict[str, Tuple[Field, bool]] = None
212+
typemap: Dict[str, Tuple[Field, bool]]
213213

214214
def __init__(self, directive: "ObjectDescription") -> None:
215215
self.directive = directive

sphinx/util/docutils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -176,8 +176,8 @@ class sphinx_domains:
176176
"""
177177
def __init__(self, env: "BuildEnvironment") -> None:
178178
self.env = env
179-
self.directive_func: Callable = None
180-
self.roles_func: Callable = None
179+
self.directive_func: Callable = lambda *args: (None, [])
180+
self.roles_func: Callable = lambda *args: (None, [])
181181

182182
def __enter__(self) -> None:
183183
self.enable()
@@ -372,7 +372,7 @@ def __call__(self, name: str, rawtext: str, text: str, lineno: int,
372372
if name:
373373
self.name = name.lower()
374374
else:
375-
self.name = self.env.temp_data.get('default_role')
375+
self.name = self.env.temp_data.get('default_role', '')
376376
if not self.name:
377377
self.name = self.env.config.default_role
378378
if not self.name:
@@ -491,7 +491,7 @@ def dispatch_departure(self, node: Node) -> None:
491491

492492
# cache a vanilla instance of nodes.document
493493
# Used in new_document() function
494-
__document_cache__: nodes.document = None
494+
__document_cache__: Optional[nodes.document] = None
495495

496496

497497
def new_document(source_path: str, settings: Any = None) -> nodes.document:

sphinx/util/logging.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,8 @@ def prefixed_warnings(prefix: str) -> Generator[None, None, None]:
320320
prefix_filter.prefix = previous
321321
else:
322322
# not prefixed yet
323+
prefix_filter = MessagePrefixFilter(prefix)
323324
try:
324-
prefix_filter = MessagePrefixFilter(prefix)
325325
warning_handler.addFilter(prefix_filter)
326326
yield
327327
finally:
@@ -472,7 +472,7 @@ class SphinxLogRecordTranslator(logging.Filter):
472472
* Make a instance of SphinxLogRecord
473473
* docname to path if location given
474474
"""
475-
LogRecordClass: Type[logging.LogRecord] = None
475+
LogRecordClass: Type[logging.LogRecord]
476476

477477
def __init__(self, app: "Sphinx") -> None:
478478
self.app = app

sphinx/util/nodes.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010

1111
import re
1212
import unicodedata
13-
from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Set, Tuple, Type, Union, cast
13+
from typing import (TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Set, Tuple, Type,
14+
Union, cast)
1415

1516
from docutils import nodes
1617
from docutils.nodes import Element, Node
@@ -170,7 +171,7 @@ def apply_source_workaround(node: Element) -> None:
170171
))):
171172
logger.debug('[i18n] PATCH: %r to have source and line: %s',
172173
get_full_module_name(node), repr_domxml(node))
173-
node.source = get_node_source(node)
174+
node.source = get_node_source(node) or ''
174175
node.line = 0 # need fix docutils to get `node.line`
175176
return
176177

@@ -266,7 +267,7 @@ def extract_messages(doctree: Element) -> Iterable[Tuple[Element, str]]:
266267
if node.get('translatable'):
267268
msg = '.. image:: %s' % node['uri']
268269
else:
269-
msg = None
270+
msg = ''
270271
elif isinstance(node, META_TYPE_NODES):
271272
msg = node.rawcontent
272273
elif isinstance(node, nodes.pending) and is_pending_meta(node):
@@ -279,14 +280,14 @@ def extract_messages(doctree: Element) -> Iterable[Tuple[Element, str]]:
279280
yield node, msg
280281

281282

282-
def get_node_source(node: Element) -> str:
283+
def get_node_source(node: Element) -> Optional[str]:
283284
for pnode in traverse_parent(node):
284285
if pnode.source:
285286
return pnode.source
286287
return None
287288

288289

289-
def get_node_line(node: Element) -> int:
290+
def get_node_line(node: Element) -> Optional[int]:
290291
for pnode in traverse_parent(node):
291292
if pnode.line:
292293
return pnode.line
@@ -300,7 +301,7 @@ def traverse_parent(node: Element, cls: Any = None) -> Iterable[Element]:
300301
node = node.parent
301302

302303

303-
def get_prev_node(node: Node) -> Node:
304+
def get_prev_node(node: Node) -> Optional[Node]:
304305
pos = node.parent.index(node)
305306
if pos > 0:
306307
return node.parent[pos - 1]
@@ -360,10 +361,11 @@ def split_explicit_title(text: str) -> Tuple[bool, str, str]:
360361
]
361362

362363

363-
def process_index_entry(entry: str, targetid: str) -> List[Tuple[str, str, str, str, str]]:
364+
def process_index_entry(entry: str, targetid: str
365+
) -> List[Tuple[str, str, str, str, Optional[str]]]:
364366
from sphinx.domains.python import pairindextypes
365367

366-
indexentries: List[Tuple[str, str, str, str, str]] = []
368+
indexentries: List[Tuple[str, str, str, str, Optional[str]]] = []
367369
entry = entry.strip()
368370
oentry = entry
369371
main = ''
@@ -531,7 +533,8 @@ def make_id(env: "BuildEnvironment", document: nodes.document,
531533
return node_id
532534

533535

534-
def find_pending_xref_condition(node: addnodes.pending_xref, condition: str) -> Element:
536+
def find_pending_xref_condition(node: addnodes.pending_xref, condition: str
537+
) -> Optional[Element]:
535538
"""Pick matched pending_xref_condition node up from the pending_xref."""
536539
for subnode in node:
537540
if (isinstance(subnode, addnodes.pending_xref_condition) and

sphinx/util/parallel.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import time
1515
import traceback
1616
from math import sqrt
17-
from typing import Any, Callable, Dict, List, Sequence
17+
from typing import Any, Callable, Dict, List, Optional, Sequence
1818

1919
try:
2020
import multiprocessing
@@ -62,7 +62,7 @@ def __init__(self, nproc: int) -> None:
6262
# (optional) function performed by each task on the result of main task
6363
self._result_funcs: Dict[int, Callable] = {}
6464
# task arguments
65-
self._args: Dict[int, List[Any]] = {}
65+
self._args: Dict[int, Optional[List[Any]]] = {}
6666
# list of subprocesses (both started and waiting)
6767
self._procs: Dict[int, multiprocessing.Process] = {}
6868
# list of receiving pipe connections of running subprocesses

sphinx/util/typing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def _evaluate(self, globalns: Dict, localns: Dict) -> Any:
6464
Tuple[List[nodes.Node], List[nodes.system_message]]]
6565

6666
# A option spec for directive
67-
OptionSpec = Dict[str, Callable[[Optional[str]], Any]]
67+
OptionSpec = Dict[str, Callable[[str], Any]]
6868

6969
# title getter functions for enumerable nodes (see sphinx.domains.std)
7070
TitleGetter = Callable[[nodes.Node], str]

0 commit comments

Comments
 (0)