Skip to content

Commit 4ef8752

Browse files
authored
[lint] change mypy imports policy. (#12017)
1 parent fde43ed commit 4ef8752

File tree

14 files changed

+62
-29
lines changed

14 files changed

+62
-29
lines changed

pyproject.toml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ lint = [
8787
"sphinx-lint",
8888
"docutils-stubs",
8989
"types-requests",
90+
"pytest>=6.0",
9091
]
9192
test = [
9293
"pytest>=6.0",
@@ -133,9 +134,6 @@ exclude = [
133134
files = ["sphinx"]
134135
check_untyped_defs = true
135136
disallow_incomplete_defs = true
136-
follow_imports = "skip"
137-
ignore_missing_imports = true
138-
no_implicit_optional = true
139137
python_version = "3.9"
140138
show_column_numbers = true
141139
show_error_context = true
@@ -152,6 +150,9 @@ enable_error_code = [
152150
"ignore-without-code",
153151
"unused-awaitable",
154152
]
153+
disable_error_code = [
154+
"import-untyped",
155+
]
155156

156157
[[tool.mypy.overrides]]
157158
module = [

sphinx/ext/autosummary/generate.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,8 @@ def __init__(self, app: Sphinx) -> None:
133133

134134
if app.translator:
135135
self.env.add_extension("jinja2.ext.i18n")
136-
self.env.install_gettext_translations(app.translator)
136+
# ``install_gettext_translations`` is injected by the ``jinja2.ext.i18n`` extension
137+
self.env.install_gettext_translations(app.translator) # type: ignore[attr-defined]
137138

138139
def render(self, template_name: str, context: dict) -> str:
139140
"""Render a template file."""

sphinx/jinja2glue.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,12 @@
88

99
from jinja2 import BaseLoader, FileSystemLoader, TemplateNotFound
1010
from jinja2.sandbox import SandboxedEnvironment
11-
from jinja2.utils import open_if_exists
11+
from jinja2.utils import open_if_exists, pass_context
1212

1313
from sphinx.application import TemplateBridge
1414
from sphinx.util import logging
1515
from sphinx.util.osutil import mtimes_of_files
1616

17-
try:
18-
from jinja2.utils import pass_context
19-
except ImportError:
20-
from jinja2 import contextfunction as pass_context
21-
2217
if TYPE_CHECKING:
2318
from collections.abc import Iterator
2419

@@ -194,7 +189,9 @@ def init(
194189
self.environment.globals['accesskey'] = pass_context(accesskey)
195190
self.environment.globals['idgen'] = idgen
196191
if use_i18n:
197-
self.environment.install_gettext_translations(builder.app.translator)
192+
# ``install_gettext_translations`` is injected by the ``jinja2.ext.i18n`` extension
193+
self.environment.install_gettext_translations( # type: ignore[attr-defined]
194+
builder.app.translator)
198195

199196
def render(self, template: str, context: dict) -> str: # type: ignore[override]
200197
return self.environment.get_template(template).render(context)
@@ -218,5 +215,6 @@ def get_source(self, environment: Environment, template: str) -> tuple[str, str,
218215
return loader.get_source(environment, template)
219216
except TemplateNotFound:
220217
pass
221-
msg = f"{template!r} not found in {self.environment.loader.pathchain}"
218+
msg = (f"{template!r} not found in "
219+
f"{self.environment.loader.pathchain}") # type: ignore[union-attr]
222220
raise TemplateNotFound(msg)

sphinx/registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
if sys.version_info >= (3, 10):
1212
from importlib.metadata import entry_points
1313
else:
14-
from importlib_metadata import entry_points
14+
from importlib_metadata import entry_points # type: ignore[import-not-found]
1515

1616
from sphinx.domains import Domain, Index, ObjType
1717
from sphinx.domains.std import GenericObject, Target

sphinx/search/ja.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,16 @@
1313
import os
1414
import re
1515
import sys
16-
from typing import TYPE_CHECKING, Any, Dict, List
16+
from typing import Any
1717

1818
try:
19-
import MeCab
19+
import MeCab # type: ignore[import-not-found]
2020
native_module = True
2121
except ImportError:
2222
native_module = False
2323

2424
try:
25-
import janome.tokenizer
25+
import janome.tokenizer # type: ignore[import-not-found]
2626
janome_module = True
2727
except ImportError:
2828
janome_module = False

sphinx/search/zh.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,13 @@
44

55
import os
66
import re
7-
from typing import TYPE_CHECKING, Dict, List
87

98
import snowballstemmer
109

1110
from sphinx.search import SearchLanguage
1211

1312
try:
14-
import jieba
13+
import jieba # type: ignore[import-not-found]
1514
JIEBA = True
1615
except ImportError:
1716
JIEBA = False

sphinx/testing/fixtures.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def app_params(request: Any, test_params: dict, shared_result: SharedResult,
8282
if test_params['shared_result']:
8383
if 'srcdir' in kwargs:
8484
msg = 'You can not specify shared_result and srcdir in same time.'
85-
raise pytest.Exception(msg)
85+
pytest.fail(msg)
8686
kwargs['srcdir'] = test_params['shared_result']
8787
restore = shared_result.restore(test_params['shared_result'])
8888
kwargs.update(restore)

sphinx/theming.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
if sys.version_info >= (3, 10):
2323
from importlib.metadata import entry_points
2424
else:
25-
from importlib_metadata import entry_points
25+
from importlib_metadata import entry_points # type: ignore[import-not-found]
2626

2727
if TYPE_CHECKING:
2828
from sphinx.application import Sphinx

sphinx/util/i18n.py

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import re
77
from datetime import datetime, timezone
88
from os import path
9-
from typing import TYPE_CHECKING, Callable, NamedTuple
9+
from typing import TYPE_CHECKING, NamedTuple
1010

1111
import babel.dates
1212
from babel.messages.mofile import write_mo
@@ -18,10 +18,41 @@
1818
from sphinx.util.osutil import SEP, canon_path, relpath
1919

2020
if TYPE_CHECKING:
21+
import datetime as dt
2122
from collections.abc import Generator
23+
from typing import Protocol, Union
24+
25+
from babel.core import Locale
2226

2327
from sphinx.environment import BuildEnvironment
2428

29+
class DateFormatter(Protocol):
30+
def __call__( # NoQA: E704
31+
self,
32+
date: dt.date | None = ...,
33+
format: str = ...,
34+
locale: str | Locale | None = ...,
35+
) -> str: ...
36+
37+
class TimeFormatter(Protocol):
38+
def __call__( # NoQA: E704
39+
self,
40+
time: dt.time | dt.datetime | float | None = ...,
41+
format: str = ...,
42+
tzinfo: dt.tzinfo | None = ...,
43+
locale: str | Locale | None = ...,
44+
) -> str: ...
45+
46+
class DatetimeFormatter(Protocol):
47+
def __call__( # NoQA: E704
48+
self,
49+
datetime: dt.date | dt.time | float | None = ...,
50+
format: str = ...,
51+
tzinfo: dt.tzinfo | None = ...,
52+
locale: str | Locale | None = ...,
53+
) -> str: ...
54+
55+
Formatter = Union[DateFormatter, TimeFormatter, DatetimeFormatter]
2556

2657
logger = logging.getLogger(__name__)
2758

@@ -169,7 +200,7 @@ def docname_to_domain(docname: str, compaction: bool | str) -> str:
169200

170201

171202
def babel_format_date(date: datetime, format: str, locale: str,
172-
formatter: Callable = babel.dates.format_date) -> str:
203+
formatter: Formatter = babel.dates.format_date) -> str:
173204
# Check if we have the tzinfo attribute. If not we cannot do any time
174205
# related formats.
175206
if not hasattr(date, 'tzinfo'):
@@ -207,6 +238,7 @@ def format_date(
207238
# Check if we have to use a different babel formatter then
208239
# format_datetime, because we only want to format a date
209240
# or a time.
241+
function: Formatter
210242
if token == '%x':
211243
function = babel.dates.format_date
212244
elif token == '%X':

sphinx/util/rst.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ def charwidth(char: str, widechars: str) -> int:
5454
def heading(env: Environment, text: str, level: int = 1) -> str:
5555
"""Create a heading for *level*."""
5656
assert level <= 3
57-
width = textwidth(text, WIDECHARS[env.language])
57+
# ``env.language`` is injected by ``sphinx.util.template.ReSTRenderer``
58+
width = textwidth(text, WIDECHARS[env.language]) # type: ignore[attr-defined]
5859
sectioning_char = SECTIONING_CHARS[level - 1]
5960
return f'{text}\n{sectioning_char * width}'
6061

0 commit comments

Comments
 (0)