mirror of
https://github.com/sphinx-doc/sphinx.git
synced 2025-02-25 18:55:22 -06:00
Add type hints to untyped definitions
This commit is contained in:
parent
82d78c19bf
commit
17c1aa76c6
11
.ruff.toml
11
.ruff.toml
@ -38,7 +38,7 @@ select = [
|
||||
"ANN003", # Missing type annotation for `**{name}`
|
||||
# "ANN101", # Missing type annotation for `{name}` in method
|
||||
# "ANN102", # Missing type annotation for `{name}` in classmethod
|
||||
# "ANN201", # Missing return type annotation for public function `{name}`
|
||||
"ANN201", # Missing return type annotation for public function `{name}`
|
||||
# "ANN202", # Missing return type annotation for private function `{name}`
|
||||
# "ANN204", # Missing return type annotation for special method `{name}`
|
||||
"ANN205", # Missing return type annotation for staticmethod `{name}`
|
||||
@ -471,6 +471,9 @@ select = [
|
||||
]
|
||||
|
||||
[lint.per-file-ignores]
|
||||
"doc/*" = [
|
||||
"ANN", # documentation doesn't need annotations
|
||||
]
|
||||
"doc/conf.py" = ["INP001"]
|
||||
"doc/development/tutorials/examples/*" = ["INP001"]
|
||||
# allow print() in the tutorial
|
||||
@ -506,8 +509,10 @@ select = [
|
||||
"tests/test_util_typing.py" = ["UP006", "UP035"]
|
||||
"tests/typing_test_data.py" = ["FA100", "UP006", "UP035"]
|
||||
|
||||
# whitelist ``print`` for stdout messages
|
||||
"utils/*" = ["T201"]
|
||||
"utils/*" = [
|
||||
"T201", # whitelist ``print`` for stdout messages
|
||||
"ANN", # utilities don't need annotations
|
||||
]
|
||||
|
||||
[lint.flake8-quotes]
|
||||
inline-quotes = "single"
|
||||
|
@ -167,7 +167,7 @@ class desc_signature(_desc_classes_injector, nodes.Part, nodes.Inline, nodes.Tex
|
||||
classes = ['sig', 'sig-object']
|
||||
|
||||
@property
|
||||
def child_text_separator(self):
|
||||
def child_text_separator(self) -> str: # type: ignore[override]
|
||||
if self.get('is_multiline'):
|
||||
return ' '
|
||||
else:
|
||||
@ -258,7 +258,7 @@ class desc_parameterlist(nodes.Part, nodes.Inline, nodes.FixedTextElement):
|
||||
"""
|
||||
child_text_separator = ', '
|
||||
|
||||
def astext(self):
|
||||
def astext(self) -> str:
|
||||
return f'({super().astext()})'
|
||||
|
||||
|
||||
@ -271,7 +271,7 @@ class desc_type_parameter_list(nodes.Part, nodes.Inline, nodes.FixedTextElement)
|
||||
"""
|
||||
child_text_separator = ', '
|
||||
|
||||
def astext(self):
|
||||
def astext(self) -> str:
|
||||
return f'[{super().astext()}]'
|
||||
|
||||
|
||||
@ -322,7 +322,7 @@ class desc_sig_element(nodes.inline, _desc_classes_injector):
|
||||
super().__init__(rawsource, text, *children, **attributes)
|
||||
self['classes'].extend(self.classes)
|
||||
|
||||
def __init_subclass__(cls, *, _sig_element=False, **kwargs: Any):
|
||||
def __init_subclass__(cls, *, _sig_element: bool = False, **kwargs: Any):
|
||||
super().__init_subclass__(**kwargs)
|
||||
if _sig_element:
|
||||
# add the class to the SIG_ELEMENTS set if asked
|
||||
|
@ -13,7 +13,7 @@ from collections import deque
|
||||
from collections.abc import Collection, Sequence # NoQA: TCH003
|
||||
from io import StringIO
|
||||
from os import path
|
||||
from typing import IO, TYPE_CHECKING, Any, Callable
|
||||
from typing import IO, TYPE_CHECKING, Any, Callable, Literal
|
||||
|
||||
from docutils.nodes import TextElement # NoQA: TCH002
|
||||
from docutils.parsers.rst import Directive, roles
|
||||
@ -1307,7 +1307,7 @@ class Sphinx:
|
||||
|
||||
return True
|
||||
|
||||
def set_html_assets_policy(self, policy):
|
||||
def set_html_assets_policy(self, policy: Literal['always', 'per_page']) -> None:
|
||||
"""Set the policy to include assets in HTML pages.
|
||||
|
||||
- always: include the assets in all the pages
|
||||
|
@ -42,7 +42,7 @@ from sphinx.util.docutils import SphinxDirective
|
||||
from sphinx.util.nodes import make_refnode
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator, Iterator
|
||||
from collections.abc import Generator, Iterator, Sequence
|
||||
|
||||
from docutils.nodes import Element, Node, TextElement, system_message
|
||||
|
||||
@ -2197,11 +2197,11 @@ class DefinitionParser(BaseParser):
|
||||
return 'C'
|
||||
|
||||
@property
|
||||
def id_attributes(self):
|
||||
def id_attributes(self) -> Sequence[str]:
|
||||
return self.config.c_id_attributes
|
||||
|
||||
@property
|
||||
def paren_attributes(self):
|
||||
def paren_attributes(self) -> Sequence[str]:
|
||||
return self.config.c_paren_attributes
|
||||
|
||||
def _parse_string(self) -> str | None:
|
||||
|
@ -43,7 +43,7 @@ from sphinx.util.docutils import SphinxDirective
|
||||
from sphinx.util.nodes import make_refnode
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator, Iterator
|
||||
from collections.abc import Generator, Iterator, Sequence
|
||||
|
||||
from docutils.nodes import Element, Node, TextElement, system_message
|
||||
|
||||
@ -2880,7 +2880,7 @@ class ASTDeclaratorMemPtr(ASTDeclarator):
|
||||
self.next.name = name
|
||||
|
||||
@property
|
||||
def isPack(self):
|
||||
def isPack(self) -> bool:
|
||||
return self.next.isPack
|
||||
|
||||
@property
|
||||
@ -2978,7 +2978,7 @@ class ASTDeclaratorParen(ASTDeclarator):
|
||||
self.inner.name = name
|
||||
|
||||
@property
|
||||
def isPack(self):
|
||||
def isPack(self) -> bool:
|
||||
return self.inner.isPack or self.next.isPack
|
||||
|
||||
@property
|
||||
@ -5240,11 +5240,11 @@ class DefinitionParser(BaseParser):
|
||||
return 'C++'
|
||||
|
||||
@property
|
||||
def id_attributes(self):
|
||||
def id_attributes(self) -> Sequence[str]:
|
||||
return self.config.cpp_id_attributes
|
||||
|
||||
@property
|
||||
def paren_attributes(self):
|
||||
def paren_attributes(self) -> Sequence[str]:
|
||||
return self.config.cpp_paren_attributes
|
||||
|
||||
def _parse_string(self) -> str:
|
||||
|
@ -155,7 +155,7 @@ def init_console(
|
||||
locale_dir = _LOCALE_DIR
|
||||
try:
|
||||
# encoding is ignored
|
||||
language, _ = locale.getlocale(locale.LC_MESSAGES)
|
||||
language, _ = locale.getlocale(locale.LC_MESSAGES) # type: ignore[attr-defined]
|
||||
except AttributeError:
|
||||
# LC_MESSAGES is not always defined. Fallback to the default language
|
||||
# in case it is not.
|
||||
|
@ -26,7 +26,7 @@ DEFAULT_ENABLED_MARKERS = [
|
||||
]
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
def pytest_configure(config: pytest.Config) -> None:
|
||||
"""Register custom markers"""
|
||||
for marker in DEFAULT_ENABLED_MARKERS:
|
||||
config.addinivalue_line('markers', marker)
|
||||
@ -175,7 +175,7 @@ def make_app(test_params: dict, monkeypatch: Any) -> Generator[Callable, None, N
|
||||
apps = []
|
||||
syspath = sys.path.copy()
|
||||
|
||||
def make(*args: Any, **kwargs: Any):
|
||||
def make(*args: Any, **kwargs: Any) -> SphinxTestApp:
|
||||
status, warning = StringIO(), StringIO()
|
||||
kwargs.setdefault('status', status)
|
||||
kwargs.setdefault('warning', warning)
|
||||
@ -226,7 +226,7 @@ def sphinx_test_tempdir(tmp_path_factory: Any) -> Path:
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def rollback_sysmodules(): # NoQA: PT004
|
||||
def rollback_sysmodules() -> Generator[None, None, None]: # NoQA: PT004
|
||||
"""
|
||||
Rollback sys.modules to its value before testing to unload modules
|
||||
during tests.
|
||||
|
@ -104,7 +104,7 @@ class FilenameUniqDict(dict):
|
||||
self._existing = state
|
||||
|
||||
|
||||
def _md5(data=b'', **_kw: Any):
|
||||
def _md5(data: bytes = b'', **_kw: Any) -> hashlib._Hash:
|
||||
"""Deprecated wrapper around hashlib.md5
|
||||
|
||||
To be removed in Sphinx 9.0
|
||||
@ -112,7 +112,7 @@ def _md5(data=b'', **_kw: Any):
|
||||
return hashlib.md5(data, usedforsecurity=False)
|
||||
|
||||
|
||||
def _sha1(data=b'', **_kw: Any):
|
||||
def _sha1(data: bytes = b'', **_kw: Any) -> hashlib._Hash:
|
||||
"""Deprecated wrapper around hashlib.sha1
|
||||
|
||||
To be removed in Sphinx 9.0
|
||||
|
@ -12,6 +12,8 @@ from sphinx import addnodes
|
||||
from sphinx.util import logging
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
from docutils.nodes import TextElement
|
||||
|
||||
from sphinx.config import Config
|
||||
@ -369,11 +371,11 @@ class BaseParser:
|
||||
################################################################################
|
||||
|
||||
@property
|
||||
def id_attributes(self):
|
||||
def id_attributes(self) -> Sequence[str]:
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
def paren_attributes(self):
|
||||
def paren_attributes(self) -> Sequence[str]:
|
||||
raise NotImplementedError
|
||||
|
||||
def _parse_balanced_token_seq(self, end: list[str]) -> str:
|
||||
|
@ -928,7 +928,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
|
||||
|
||||
# See Docutils r9413
|
||||
# Re-instate the footnote-reference class
|
||||
def visit_footnote_reference(self, node):
|
||||
def visit_footnote_reference(self, node: Element) -> None:
|
||||
href = '#' + node['refid']
|
||||
classes = ['footnote-reference', self.settings.footnote_references]
|
||||
self.body.append(self.starttag(node, 'a', suffix='', classes=classes,
|
||||
|
@ -70,7 +70,7 @@ OPTIONS_MAP = {
|
||||
KEYWORDS = {**DEFAULT_KEYWORDS, '_': None, '__': None}
|
||||
|
||||
|
||||
def run_extract():
|
||||
def run_extract() -> None:
|
||||
"""Message extraction function."""
|
||||
log = _get_logger()
|
||||
|
||||
@ -115,7 +115,7 @@ def run_extract():
|
||||
write_po(outfile, catalogue)
|
||||
|
||||
|
||||
def run_update():
|
||||
def run_update() -> None:
|
||||
"""Catalog merging command."""
|
||||
|
||||
log = _get_logger()
|
||||
@ -150,7 +150,7 @@ def run_update():
|
||||
os.replace(tmp_name, filename)
|
||||
|
||||
|
||||
def run_compile():
|
||||
def run_compile() -> None:
|
||||
"""
|
||||
Catalog compilation command.
|
||||
|
||||
|
@ -34,7 +34,7 @@ for file in DOCKERFILE_BASE, DOCKERFILE_LATEXPDF:
|
||||
file.write_text(content, encoding='utf-8')
|
||||
|
||||
|
||||
def git(*args: str):
|
||||
def git(*args: str) -> None:
|
||||
ret = subprocess.run(('git', *args),
|
||||
capture_output=True,
|
||||
cwd=DOCKER_ROOT,
|
||||
|
@ -21,7 +21,7 @@ def stringify_version(version_info, in_develop=True):
|
||||
return version
|
||||
|
||||
|
||||
def bump_version(path, version_info, in_develop=True):
|
||||
def bump_version(path, version_info, in_develop=True) -> None:
|
||||
version = stringify_version(version_info, in_develop)
|
||||
|
||||
with open(path, encoding='utf-8') as f:
|
||||
@ -91,7 +91,7 @@ class Changes:
|
||||
self.path = path
|
||||
self.fetch_version()
|
||||
|
||||
def fetch_version(self):
|
||||
def fetch_version(self) -> None:
|
||||
with open(self.path, encoding='utf-8') as f:
|
||||
version = f.readline().strip()
|
||||
matched = re.search(r'^Release (.*) \((.*)\)$', version)
|
||||
@ -105,7 +105,7 @@ class Changes:
|
||||
else:
|
||||
self.in_development = False
|
||||
|
||||
def finalize_release_date(self):
|
||||
def finalize_release_date(self) -> None:
|
||||
release_date = time.strftime('%b %d, %Y')
|
||||
heading = f'Release {self.version} (released {release_date})'
|
||||
|
||||
@ -120,7 +120,7 @@ class Changes:
|
||||
f.write('=' * len(heading) + '\n')
|
||||
f.write(self.filter_empty_sections(body))
|
||||
|
||||
def add_release(self, version_info):
|
||||
def add_release(self, version_info) -> None:
|
||||
if version_info[-2:] in (('beta', 0), ('final', 0)):
|
||||
version = stringify_version(version_info)
|
||||
else:
|
||||
@ -158,7 +158,7 @@ def parse_options(argv):
|
||||
return options
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
options = parse_options(sys.argv[1:])
|
||||
|
||||
with processing("Rewriting sphinx/__init__.py"):
|
||||
|
Loading…
Reference in New Issue
Block a user