Skip to content

Commit c35b911

Browse files
Fix strict mypy errors in plugin and scripts (#363)
This is a precondition for enabling mypy self-check in CI. * Fixed strict mypy errors in mypy_drf_plugin and scripts * Harmonized a few things in scripts/typecheck_tests.py with related code in django-stubs --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 44f0e94 commit c35b911

File tree

3 files changed

+24
-18
lines changed

3 files changed

+24
-18
lines changed

mypy_drf_plugin/main.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Callable, Dict, Optional
1+
from typing import Callable, Dict, Optional, Type
22

33
from mypy.nodes import TypeInfo
44
from mypy.options import Options
@@ -28,9 +28,10 @@ def __init__(self, options: Options) -> None:
2828
def _get_currently_defined_serializers(self) -> Dict[str, int]:
2929
base_serializer_sym = self.lookup_fully_qualified(fullnames.BASE_SERIALIZER_FULLNAME)
3030
if base_serializer_sym is not None and isinstance(base_serializer_sym.node, TypeInfo):
31-
return base_serializer_sym.node.metadata.setdefault("drf", {}).setdefault(
31+
serializer_bases: Dict[str, int] = base_serializer_sym.node.metadata.setdefault("drf", {}).setdefault(
3232
"serializer_bases", {fullnames.BASE_SERIALIZER_FULLNAME: 1}
3333
)
34+
return serializer_bases
3435
else:
3536
return {}
3637

@@ -40,5 +41,5 @@ def get_base_class_hook(self, fullname: str) -> Optional[Callable[[ClassDefConte
4041
return None
4142

4243

43-
def plugin(version):
44+
def plugin(version: str) -> Type[NewSemanalDRFPlugin]:
4445
return NewSemanalDRFPlugin

scripts/git_helpers.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
from typing import Optional
1+
from typing import Optional, Union
22

3-
from git import RemoteProgress, Repo
3+
from git.remote import RemoteProgress
4+
from git.repo import Repo
45

56
from scripts.paths import DRF_SOURCE_DIRECTORY
67

@@ -9,7 +10,9 @@ class ProgressPrinter(RemoteProgress):
910
def line_dropped(self, line: str) -> None:
1011
print(line)
1112

12-
def update(self, op_code, cur_count, max_count=None, message=""):
13+
def update(
14+
self, op_code: int, cur_count: Union[str, float], max_count: Union[str, float, None] = None, message: str = ""
15+
) -> None:
1316
print(self._cur_line)
1417

1518

@@ -19,7 +22,7 @@ def git_checkout_drf(commit_ref: Optional[str] = None) -> None:
1922
repository = Repo.clone_from(
2023
"https://github.com/encode/django-rest-framework.git",
2124
DRF_SOURCE_DIRECTORY,
22-
progress=ProgressPrinter(),
25+
progress=ProgressPrinter(), # type: ignore
2326
branch="master",
2427
depth=100,
2528
)

scripts/typecheck_tests.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from argparse import ArgumentParser
66
from collections import defaultdict
77
from distutils import dir_util, spawn
8-
from typing import Dict, List, Pattern, Union
8+
from typing import DefaultDict, List, Pattern, Union
99

1010
from scripts.git_helpers import git_checkout_drf
1111
from scripts.paths import DRF_SOURCE_DIRECTORY, PROJECT_DIRECTORY, STUBS_DIRECTORY
@@ -14,8 +14,8 @@
1414
# This should be updated periodically or after every DRF release.
1515
DRF_GIT_REF = "22d206c1e0dbc03840c4d190f7eda537c0f2010a"
1616

17-
IGNORED_MODULES = []
18-
MOCK_OBJECTS = [
17+
IGNORED_MODULES: List[str] = []
18+
MOCK_OBJECTS: List[str] = [
1919
"MockQueryset",
2020
"MockRequest",
2121
"TypeErrorQueryset",
@@ -253,8 +253,10 @@
253253
"utils.py": ['Invalid signature "Callable[[BadType], Any]"'],
254254
}
255255

256+
_DictToSearch = DefaultDict[str, DefaultDict[Union[str, Pattern[str]], int]]
256257

257-
def get_unused_ignores(ignored_message_freq: Dict[str, Dict[Union[str, Pattern], int]]) -> List[str]:
258+
259+
def get_unused_ignores(ignored_message_freq: _DictToSearch) -> List[str]:
258260
unused_ignores = []
259261
for root_key, patterns in IGNORED_ERRORS.items():
260262
for pattern in patterns:
@@ -265,7 +267,7 @@ def get_unused_ignores(ignored_message_freq: Dict[str, Dict[Union[str, Pattern],
265267
return unused_ignores
266268

267269

268-
def is_pattern_fits(pattern: Union[Pattern, str], line: str):
270+
def does_pattern_fit(pattern: Union[Pattern[str], str], line: str) -> bool:
269271
if isinstance(pattern, Pattern):
270272
if pattern.search(line):
271273
return True
@@ -275,15 +277,15 @@ def is_pattern_fits(pattern: Union[Pattern, str], line: str):
275277
return False
276278

277279

278-
def is_ignored(line: str, filename: str, ignored_message_dict: Dict[str, Dict[str, int]]) -> bool:
280+
def is_ignored(line: str, filename: str, *, ignored_message_freqs: _DictToSearch) -> bool:
279281
if "runtests" in line or filename in IGNORED_MODULES:
280282
return True
281283
for pattern in IGNORED_ERRORS["__common__"]:
282284
if pattern in line:
283285
return True
284286
for pattern in IGNORED_ERRORS.get(filename, []):
285-
if is_pattern_fits(pattern, line):
286-
ignored_message_dict[test_filename][pattern] += 1
287+
if does_pattern_fit(pattern, line):
288+
ignored_message_freqs[test_filename][pattern] += 1
287289
return True
288290
for mock_object in MOCK_OBJECTS:
289291
if mock_object in line:
@@ -322,13 +324,13 @@ def update(self, op_code, cur_count, max_count=None, message=""):
322324
mypy_executable = spawn.find_executable("mypy")
323325
mypy_argv = [mypy_executable, *mypy_options]
324326
completed = subprocess.run(
325-
mypy_argv,
327+
mypy_argv, # type: ignore
326328
env={"PYTHONPATH": str(PROJECT_DIRECTORY)},
327329
stdout=subprocess.PIPE,
328330
stderr=subprocess.STDOUT,
329331
)
330332
output = completed.stdout.decode()
331-
ignored_message_freqs = defaultdict(lambda: defaultdict(int))
333+
ignored_message_freqs: _DictToSearch = defaultdict(lambda: defaultdict(int))
332334
sorted_lines = sorted(output.splitlines())
333335
for line in sorted_lines:
334336
try:
@@ -337,7 +339,7 @@ def update(self, op_code, cur_count, max_count=None, message=""):
337339
except IndexError:
338340
test_filename = "unknown"
339341

340-
if not is_ignored(line, test_filename, ignored_message_dict=ignored_message_freqs):
342+
if not is_ignored(line, test_filename, ignored_message_freqs=ignored_message_freqs):
341343
global_rc = 1
342344
print(line)
343345

0 commit comments

Comments
 (0)