mirror of
https://github.com/sphinx-doc/sphinx.git
synced 2025-02-25 18:55:22 -06:00
refactor: Add Optional to type annotations
This commit is contained in:
parent
5c14375365
commit
a24ef1f0cc
@ -8,6 +8,8 @@
|
|||||||
:license: BSD, see LICENSE for details.
|
:license: BSD, see LICENSE for details.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
from docutils.writers.latex2e import Babel
|
from docutils.writers.latex2e import Babel
|
||||||
|
|
||||||
|
|
||||||
@ -40,7 +42,7 @@ class ExtBabel(Babel):
|
|||||||
self.supported = False
|
self.supported = False
|
||||||
return 'english' # fallback to english
|
return 'english' # fallback to english
|
||||||
|
|
||||||
def get_mainlanguage_options(self) -> str:
|
def get_mainlanguage_options(self) -> Optional[str]:
|
||||||
"""Return options for polyglossia's ``\\setmainlanguage``."""
|
"""Return options for polyglossia's ``\\setmainlanguage``."""
|
||||||
if self.use_polyglossia is False:
|
if self.use_polyglossia is False:
|
||||||
return None
|
return None
|
||||||
|
@ -73,6 +73,6 @@ class DeprecatedDict(dict):
|
|||||||
warnings.warn(self.message, self.warning, stacklevel=2)
|
warnings.warn(self.message, self.warning, stacklevel=2)
|
||||||
return super().get(key, default)
|
return super().get(key, default)
|
||||||
|
|
||||||
def update(self, other: Dict = None) -> None: # type: ignore
|
def update(self, other: Dict) -> None: # type: ignore
|
||||||
warnings.warn(self.message, self.warning, stacklevel=2)
|
warnings.warn(self.message, self.warning, stacklevel=2)
|
||||||
super().update(other)
|
super().update(other)
|
||||||
|
@ -11,7 +11,7 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import collections
|
import collections
|
||||||
from typing import Any, Iterable
|
from typing import Any, Iterable, Optional
|
||||||
|
|
||||||
|
|
||||||
class peek_iter:
|
class peek_iter:
|
||||||
@ -62,7 +62,7 @@ class peek_iter:
|
|||||||
def __next__(self, n: int = None) -> Any:
|
def __next__(self, n: int = None) -> Any:
|
||||||
return self.next(n)
|
return self.next(n)
|
||||||
|
|
||||||
def _fillcache(self, n: int) -> None:
|
def _fillcache(self, n: Optional[int]) -> None:
|
||||||
"""Cache `n` items. If `n` is 0 or None, then 1 item is cached."""
|
"""Cache `n` items. If `n` is 0 or None, then 1 item is cached."""
|
||||||
if not n:
|
if not n:
|
||||||
n = 1
|
n = 1
|
||||||
@ -123,7 +123,7 @@ class peek_iter:
|
|||||||
result = [self._cache.popleft() for i in range(n)]
|
result = [self._cache.popleft() for i in range(n)]
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def peek(self, n: int = None) -> Any:
|
def peek(self, n: Optional[int] = None) -> Any:
|
||||||
"""Preview the next item or `n` items of the iterator.
|
"""Preview the next item or `n` items of the iterator.
|
||||||
|
|
||||||
The iterator is not advanced when peek is called.
|
The iterator is not advanced when peek is called.
|
||||||
@ -220,7 +220,7 @@ class modify_iter(peek_iter):
|
|||||||
'modifier must be callable')
|
'modifier must be callable')
|
||||||
super().__init__(*args)
|
super().__init__(*args)
|
||||||
|
|
||||||
def _fillcache(self, n: int) -> None:
|
def _fillcache(self, n: Optional[int]) -> None:
|
||||||
"""Cache `n` modified items. If `n` is 0 or None, 1 item is cached.
|
"""Cache `n` modified items. If `n` is 0 or None, 1 item is cached.
|
||||||
|
|
||||||
Each item returned by the iterator is passed through the
|
Each item returned by the iterator is passed through the
|
||||||
|
@ -12,7 +12,7 @@ import gettext
|
|||||||
import locale
|
import locale
|
||||||
from collections import UserString, defaultdict
|
from collections import UserString, defaultdict
|
||||||
from gettext import NullTranslations
|
from gettext import NullTranslations
|
||||||
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
|
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
|
||||||
|
|
||||||
|
|
||||||
class _TranslationProxy(UserString):
|
class _TranslationProxy(UserString):
|
||||||
@ -173,7 +173,7 @@ def init_console(locale_dir: str, catalog: str) -> Tuple[NullTranslations, bool]
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# encoding is ignored
|
# encoding is ignored
|
||||||
language, _ = locale.getlocale(locale.LC_MESSAGES)
|
language, _ = locale.getlocale(locale.LC_MESSAGES) # type: Tuple[Optional[str], Any]
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
# LC_MESSAGES is not always defined. Fallback to the default language
|
# LC_MESSAGES is not always defined. Fallback to the default language
|
||||||
# in case it is not.
|
# in case it is not.
|
||||||
|
@ -58,7 +58,7 @@ def parse(code: str, mode: str = 'exec') -> "ast.AST":
|
|||||||
return ast.parse(code, mode=mode)
|
return ast.parse(code, mode=mode)
|
||||||
|
|
||||||
|
|
||||||
def unparse(node: ast.AST) -> str:
|
def unparse(node: Optional[ast.AST]) -> Optional[str]:
|
||||||
"""Unparse an AST to string."""
|
"""Unparse an AST to string."""
|
||||||
if node is None:
|
if node is None:
|
||||||
return None
|
return None
|
||||||
@ -138,7 +138,7 @@ def _unparse_arg(arg: ast.arg, default: Optional[ast.AST]) -> str:
|
|||||||
|
|
||||||
def unparse_arguments(node: ast.arguments) -> str:
|
def unparse_arguments(node: ast.arguments) -> str:
|
||||||
"""Unparse an arguments to string."""
|
"""Unparse an arguments to string."""
|
||||||
defaults = list(node.defaults)
|
defaults = list(node.defaults) # type: List[Optional[ast.AST]]
|
||||||
positionals = len(node.args)
|
positionals = len(node.args)
|
||||||
posonlyargs = 0
|
posonlyargs = 0
|
||||||
if hasattr(node, "posonlyargs"): # for py38+
|
if hasattr(node, "posonlyargs"): # for py38+
|
||||||
@ -147,7 +147,7 @@ def unparse_arguments(node: ast.arguments) -> str:
|
|||||||
for _ in range(len(defaults), positionals):
|
for _ in range(len(defaults), positionals):
|
||||||
defaults.insert(0, None)
|
defaults.insert(0, None)
|
||||||
|
|
||||||
kw_defaults = list(node.kw_defaults)
|
kw_defaults = list(node.kw_defaults) # type: List[Optional[ast.AST]]
|
||||||
for _ in range(len(kw_defaults), len(node.kwonlyargs)):
|
for _ in range(len(kw_defaults), len(node.kwonlyargs)):
|
||||||
kw_defaults.insert(0, None)
|
kw_defaults.insert(0, None)
|
||||||
|
|
||||||
|
@ -12,7 +12,7 @@ import base64
|
|||||||
import imghdr
|
import imghdr
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from os import path
|
from os import path
|
||||||
from typing import IO, NamedTuple, Tuple
|
from typing import IO, NamedTuple, Optional, Tuple
|
||||||
|
|
||||||
import imagesize
|
import imagesize
|
||||||
|
|
||||||
@ -36,7 +36,7 @@ DataURI = NamedTuple('DataURI', [('mimetype', str),
|
|||||||
('data', bytes)])
|
('data', bytes)])
|
||||||
|
|
||||||
|
|
||||||
def get_image_size(filename: str) -> Tuple[int, int]:
|
def get_image_size(filename: str) -> Optional[Tuple[int, int]]:
|
||||||
try:
|
try:
|
||||||
size = imagesize.get(filename)
|
size = imagesize.get(filename)
|
||||||
if size[0] == -1:
|
if size[0] == -1:
|
||||||
@ -53,7 +53,7 @@ def get_image_size(filename: str) -> Tuple[int, int]:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def guess_mimetype_for_stream(stream: IO, default: str = None) -> str:
|
def guess_mimetype_for_stream(stream: IO, default: Optional[str] = None) -> Optional[str]:
|
||||||
imgtype = imghdr.what(stream) # type: ignore
|
imgtype = imghdr.what(stream) # type: ignore
|
||||||
if imgtype:
|
if imgtype:
|
||||||
return 'image/' + imgtype
|
return 'image/' + imgtype
|
||||||
@ -61,7 +61,7 @@ def guess_mimetype_for_stream(stream: IO, default: str = None) -> str:
|
|||||||
return default
|
return default
|
||||||
|
|
||||||
|
|
||||||
def guess_mimetype(filename: str = '', default: str = None) -> str:
|
def guess_mimetype(filename: str = '', default: Optional[str] = None) -> Optional[str]:
|
||||||
_, ext = path.splitext(filename.lower())
|
_, ext = path.splitext(filename.lower())
|
||||||
if ext in mime_suffixes:
|
if ext in mime_suffixes:
|
||||||
return mime_suffixes[ext]
|
return mime_suffixes[ext]
|
||||||
@ -72,7 +72,7 @@ def guess_mimetype(filename: str = '', default: str = None) -> str:
|
|||||||
return default
|
return default
|
||||||
|
|
||||||
|
|
||||||
def get_image_extension(mimetype: str) -> str:
|
def get_image_extension(mimetype: str) -> Optional[str]:
|
||||||
for ext, _mimetype in mime_suffixes.items():
|
for ext, _mimetype in mime_suffixes.items():
|
||||||
if mimetype == _mimetype:
|
if mimetype == _mimetype:
|
||||||
return ext
|
return ext
|
||||||
@ -80,7 +80,7 @@ def get_image_extension(mimetype: str) -> str:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def parse_data_uri(uri: str) -> DataURI:
|
def parse_data_uri(uri: str) -> Optional[DataURI]:
|
||||||
if not uri.startswith('data:'):
|
if not uri.startswith('data:'):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@ -101,7 +101,7 @@ def parse_data_uri(uri: str) -> DataURI:
|
|||||||
return DataURI(mimetype, charset, image_data)
|
return DataURI(mimetype, charset, image_data)
|
||||||
|
|
||||||
|
|
||||||
def test_svg(h: bytes, f: IO) -> str:
|
def test_svg(h: bytes, f: IO) -> Optional[str]:
|
||||||
"""An additional imghdr library helper; test the header is SVG's or not."""
|
"""An additional imghdr library helper; test the header is SVG's or not."""
|
||||||
try:
|
try:
|
||||||
if '<svg' in h.decode().lower():
|
if '<svg' in h.decode().lower():
|
||||||
|
@ -20,7 +20,7 @@ from inspect import ( # NOQA
|
|||||||
Parameter, isclass, ismethod, ismethoddescriptor
|
Parameter, isclass, ismethod, ismethoddescriptor
|
||||||
)
|
)
|
||||||
from io import StringIO
|
from io import StringIO
|
||||||
from typing import Any, Callable, Mapping, List, Tuple
|
from typing import Any, Callable, Mapping, List, Optional, Tuple
|
||||||
from typing import cast
|
from typing import cast
|
||||||
|
|
||||||
from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
|
from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
|
||||||
@ -565,7 +565,7 @@ class Signature:
|
|||||||
self.partialmethod_with_noargs = False
|
self.partialmethod_with_noargs = False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.signature = inspect.signature(subject)
|
self.signature = inspect.signature(subject) # type: Optional[inspect.Signature]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
# Until python 3.6.4, cpython has been crashed on inspection for
|
# Until python 3.6.4, cpython has been crashed on inspection for
|
||||||
# partialmethods not having any arguments.
|
# partialmethods not having any arguments.
|
||||||
|
@ -18,7 +18,7 @@ import sys
|
|||||||
import warnings
|
import warnings
|
||||||
from io import StringIO
|
from io import StringIO
|
||||||
from os import path
|
from os import path
|
||||||
from typing import Any, Generator, Iterator, List, Tuple
|
from typing import Any, Generator, Iterator, List, Optional, Tuple
|
||||||
|
|
||||||
from sphinx.deprecation import RemovedInSphinx40Warning
|
from sphinx.deprecation import RemovedInSphinx40Warning
|
||||||
|
|
||||||
@ -206,7 +206,7 @@ class FileAvoidWrite:
|
|||||||
"""
|
"""
|
||||||
def __init__(self, path: str) -> None:
|
def __init__(self, path: str) -> None:
|
||||||
self._path = path
|
self._path = path
|
||||||
self._io = None # type: StringIO
|
self._io = None # type: Optional[StringIO]
|
||||||
|
|
||||||
def write(self, data: str) -> None:
|
def write(self, data: str) -> None:
|
||||||
if not self._io:
|
if not self._io:
|
||||||
|
@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
import binascii
|
import binascii
|
||||||
import struct
|
import struct
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
LEN_IEND = 12
|
LEN_IEND = 12
|
||||||
@ -20,7 +21,7 @@ DEPTH_CHUNK_START = b'tEXtDepth\x00'
|
|||||||
IEND_CHUNK = b'\x00\x00\x00\x00IEND\xAE\x42\x60\x82'
|
IEND_CHUNK = b'\x00\x00\x00\x00IEND\xAE\x42\x60\x82'
|
||||||
|
|
||||||
|
|
||||||
def read_png_depth(filename: str) -> int:
|
def read_png_depth(filename: str) -> Optional[int]:
|
||||||
"""Read the special tEXt chunk indicating the depth from a PNG file."""
|
"""Read the special tEXt chunk indicating the depth from a PNG file."""
|
||||||
with open(filename, 'rb') as f:
|
with open(filename, 'rb') as f:
|
||||||
f.seek(- (LEN_IEND + LEN_DEPTH), 2)
|
f.seek(- (LEN_IEND + LEN_DEPTH), 2)
|
||||||
|
Loading…
Reference in New Issue
Block a user