Skip to content

Commit 23ee1e7

Browse files
authored
Use builtin generics and PEP 604 for type annotations wherever possible (#13427)
1 parent 3ec1849 commit 23ee1e7

File tree

197 files changed

+3824
-4239
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

197 files changed

+3824
-4239
lines changed

misc/actions_stubs.py

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

55
import os
66
import shutil
7-
from typing import Any, Tuple
7+
from typing import Any
88

99
try:
1010
import click
@@ -20,7 +20,7 @@ def apply_all(
2020
directory: str,
2121
extension: str,
2222
to_extension: str = "",
23-
exclude: Tuple[str] = ("",),
23+
exclude: tuple[str] = ("",),
2424
recursive: bool = True,
2525
debug: bool = False,
2626
) -> None:
@@ -100,7 +100,7 @@ def main(
100100
directory: str,
101101
extension: str,
102102
to_extension: str,
103-
exclude: Tuple[str],
103+
exclude: tuple[str],
104104
not_recursive: bool,
105105
) -> None:
106106
"""

misc/analyze_cache.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import os
77
import os.path
88
from collections import Counter
9-
from typing import Any, Dict, Iterable, List, Optional
9+
from typing import Any, Dict, Iterable
1010
from typing_extensions import Final, TypeAlias as _TypeAlias
1111

1212
ROOT: Final = ".mypy_cache/3.5"
@@ -75,18 +75,18 @@ def pluck(name: str, chunks: Iterable[JsonDict]) -> Iterable[JsonDict]:
7575
return (chunk for chunk in chunks if chunk[".class"] == name)
7676

7777

78-
def report_counter(counter: Counter, amount: Optional[int] = None) -> None:
78+
def report_counter(counter: Counter, amount: int | None = None) -> None:
7979
for name, count in counter.most_common(amount):
8080
print(f" {count: <8} {name}")
8181
print()
8282

8383

84-
def report_most_common(chunks: List[JsonDict], amount: Optional[int] = None) -> None:
84+
def report_most_common(chunks: list[JsonDict], amount: int | None = None) -> None:
8585
report_counter(Counter(str(chunk) for chunk in chunks), amount)
8686

8787

8888
def compress(chunk: JsonDict) -> JsonDict:
89-
cache = {} # type: Dict[int, JsonDict]
89+
cache: dict[int, JsonDict] = {}
9090
counter = 0
9191

9292
def helper(chunk: Any) -> Any:
@@ -119,7 +119,7 @@ def helper(chunk: Any) -> Any:
119119

120120

121121
def decompress(chunk: JsonDict) -> JsonDict:
122-
cache = {} # type: Dict[int, JsonDict]
122+
cache: dict[int, JsonDict] = {}
123123

124124
def helper(chunk: Any) -> Any:
125125
if not isinstance(chunk, dict):

misc/diff-cache.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import os
1313
import sys
1414
from collections import defaultdict
15-
from typing import Any, Dict, Optional, Set
15+
from typing import Any
1616

1717
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1818

@@ -26,7 +26,7 @@ def make_cache(input_dir: str, sqlite: bool) -> MetadataStore:
2626
return FilesystemMetadataStore(input_dir)
2727

2828

29-
def merge_deps(all: Dict[str, Set[str]], new: Dict[str, Set[str]]) -> None:
29+
def merge_deps(all: dict[str, set[str]], new: dict[str, set[str]]) -> None:
3030
for k, v in new.items():
3131
all.setdefault(k, set()).update(v)
3232

@@ -70,13 +70,13 @@ def main() -> None:
7070
cache1 = make_cache(args.input_dir1, args.sqlite)
7171
cache2 = make_cache(args.input_dir2, args.sqlite)
7272

73-
type_misses: Dict[str, int] = defaultdict(int)
74-
type_hits: Dict[str, int] = defaultdict(int)
73+
type_misses: dict[str, int] = defaultdict(int)
74+
type_hits: dict[str, int] = defaultdict(int)
7575

76-
updates: Dict[str, Optional[str]] = {}
76+
updates: dict[str, str | None] = {}
7777

78-
deps1: Dict[str, Set[str]] = {}
79-
deps2: Dict[str, Set[str]] = {}
78+
deps1: dict[str, set[str]] = {}
79+
deps2: dict[str, set[str]] = {}
8080

8181
misses = hits = 0
8282
cache1_all = list(cache1.list_all())

misc/dump-ast.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,14 @@
77

88
import argparse
99
import sys
10-
from typing import Tuple
1110

1211
from mypy import defaults
1312
from mypy.errors import CompileError
1413
from mypy.options import Options
1514
from mypy.parse import parse
1615

1716

18-
def dump(fname: str, python_version: Tuple[int, int], quiet: bool = False) -> None:
17+
def dump(fname: str, python_version: tuple[int, int], quiet: bool = False) -> None:
1918
options = Options()
2019
options.python_version = python_version
2120
with open(fname, "rb") as f:

misc/incremental_checker.py

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
import textwrap
4545
import time
4646
from argparse import ArgumentParser, Namespace, RawDescriptionHelpFormatter
47-
from typing import Any, Dict, List, Optional, Tuple
47+
from typing import Any, Dict, Tuple
4848
from typing_extensions import TypeAlias as _TypeAlias
4949

5050
CACHE_PATH: Final = ".incremental_checker_cache.json"
@@ -66,7 +66,7 @@ def delete_folder(folder_path: str) -> None:
6666
shutil.rmtree(folder_path)
6767

6868

69-
def execute(command: List[str], fail_on_error: bool = True) -> Tuple[str, str, int]:
69+
def execute(command: list[str], fail_on_error: bool = True) -> tuple[str, str, int]:
7070
proc = subprocess.Popen(
7171
" ".join(command), stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True
7272
)
@@ -98,7 +98,7 @@ def initialize_repo(repo_url: str, temp_repo_path: str, branch: str) -> None:
9898
execute(["git", "-C", temp_repo_path, "checkout", branch])
9999

100100

101-
def get_commits(repo_folder_path: str, commit_range: str) -> List[Tuple[str, str]]:
101+
def get_commits(repo_folder_path: str, commit_range: str) -> list[tuple[str, str]]:
102102
raw_data, _stderr, _errcode = execute(
103103
["git", "-C", repo_folder_path, "log", "--reverse", "--oneline", commit_range]
104104
)
@@ -109,25 +109,25 @@ def get_commits(repo_folder_path: str, commit_range: str) -> List[Tuple[str, str
109109
return output
110110

111111

112-
def get_commits_starting_at(repo_folder_path: str, start_commit: str) -> List[Tuple[str, str]]:
112+
def get_commits_starting_at(repo_folder_path: str, start_commit: str) -> list[tuple[str, str]]:
113113
print(f"Fetching commits starting at {start_commit}")
114114
return get_commits(repo_folder_path, f"{start_commit}^..HEAD")
115115

116116

117-
def get_nth_commit(repo_folder_path: str, n: int) -> Tuple[str, str]:
117+
def get_nth_commit(repo_folder_path: str, n: int) -> tuple[str, str]:
118118
print(f"Fetching last {n} commits (or all, if there are fewer commits than n)")
119119
return get_commits(repo_folder_path, f"-{n}")[0]
120120

121121

122122
def run_mypy(
123-
target_file_path: Optional[str],
123+
target_file_path: str | None,
124124
mypy_cache_path: str,
125-
mypy_script: Optional[str],
125+
mypy_script: str | None,
126126
*,
127127
incremental: bool = False,
128128
daemon: bool = False,
129129
verbose: bool = False,
130-
) -> Tuple[float, str, Dict[str, Any]]:
130+
) -> tuple[float, str, dict[str, Any]]:
131131
"""Runs mypy against `target_file_path` and returns what mypy prints to stdout as a string.
132132
133133
If `incremental` is set to True, this function will use store and retrieve all caching data
@@ -136,7 +136,7 @@ def run_mypy(
136136
137137
If `daemon` is True, we use daemon mode; the daemon must be started and stopped by the caller.
138138
"""
139-
stats = {} # type: Dict[str, Any]
139+
stats: dict[str, Any] = {}
140140
if daemon:
141141
command = DAEMON_CMD + ["check", "-v"]
142142
else:
@@ -162,8 +162,8 @@ def run_mypy(
162162
return runtime, output, stats
163163

164164

165-
def filter_daemon_stats(output: str) -> Tuple[str, Dict[str, Any]]:
166-
stats = {} # type: Dict[str, Any]
165+
def filter_daemon_stats(output: str) -> tuple[str, dict[str, Any]]:
166+
stats: dict[str, Any] = {}
167167
lines = output.splitlines()
168168
output_lines = []
169169
for line in lines:
@@ -208,12 +208,12 @@ def save_cache(cache: JsonDict, incremental_cache_path: str = CACHE_PATH) -> Non
208208

209209

210210
def set_expected(
211-
commits: List[Tuple[str, str]],
211+
commits: list[tuple[str, str]],
212212
cache: JsonDict,
213213
temp_repo_path: str,
214-
target_file_path: Optional[str],
214+
target_file_path: str | None,
215215
mypy_cache_path: str,
216-
mypy_script: Optional[str],
216+
mypy_script: str | None,
217217
) -> None:
218218
"""Populates the given `cache` with the expected results for all of the given `commits`.
219219
@@ -241,13 +241,13 @@ def set_expected(
241241

242242

243243
def test_incremental(
244-
commits: List[Tuple[str, str]],
244+
commits: list[tuple[str, str]],
245245
cache: JsonDict,
246246
temp_repo_path: str,
247-
target_file_path: Optional[str],
247+
target_file_path: str | None,
248248
mypy_cache_path: str,
249249
*,
250-
mypy_script: Optional[str] = None,
250+
mypy_script: str | None = None,
251251
daemon: bool = False,
252252
exit_on_error: bool = False,
253253
) -> None:
@@ -258,16 +258,16 @@ def test_incremental(
258258
"""
259259
print("Note: first commit is evaluated twice to warm up cache")
260260
commits = [commits[0]] + commits
261-
overall_stats = {} # type: Dict[str, float]
261+
overall_stats: dict[str, float] = {}
262262
for commit_id, message in commits:
263263
print(f'Now testing commit {commit_id}: "{message}"')
264264
execute(["git", "-C", temp_repo_path, "checkout", commit_id])
265265
runtime, output, stats = run_mypy(
266266
target_file_path, mypy_cache_path, mypy_script, incremental=True, daemon=daemon
267267
)
268268
relevant_stats = combine_stats(overall_stats, stats)
269-
expected_runtime = cache[commit_id]["runtime"] # type: float
270-
expected_output = cache[commit_id]["output"] # type: str
269+
expected_runtime: float = cache[commit_id]["runtime"]
270+
expected_output: str = cache[commit_id]["output"]
271271
if output != expected_output:
272272
print(" Output does not match expected result!")
273273
print(f" Expected output ({expected_runtime:.3f} sec):")
@@ -286,10 +286,10 @@ def test_incremental(
286286
print("Overall stats:", overall_stats)
287287

288288

289-
def combine_stats(overall_stats: Dict[str, float], new_stats: Dict[str, Any]) -> Dict[str, float]:
289+
def combine_stats(overall_stats: dict[str, float], new_stats: dict[str, Any]) -> dict[str, float]:
290290
INTERESTING_KEYS = ["build_time", "gc_time"]
291291
# For now, we only support float keys
292-
relevant_stats = {} # type: Dict[str, float]
292+
relevant_stats: dict[str, float] = {}
293293
for key in INTERESTING_KEYS:
294294
if key in new_stats:
295295
value = float(new_stats[key])
@@ -306,7 +306,7 @@ def cleanup(temp_repo_path: str, mypy_cache_path: str) -> None:
306306
def test_repo(
307307
target_repo_url: str,
308308
temp_repo_path: str,
309-
target_file_path: Optional[str],
309+
target_file_path: str | None,
310310
mypy_path: str,
311311
incremental_cache_path: str,
312312
mypy_cache_path: str,
@@ -391,9 +391,7 @@ def test_repo(
391391

392392

393393
def main() -> None:
394-
help_factory = lambda prog: RawDescriptionHelpFormatter(
395-
prog=prog, max_help_position=32
396-
) # type: Any
394+
help_factory: Any = lambda prog: RawDescriptionHelpFormatter(prog=prog, max_help_position=32)
397395
parser = ArgumentParser(
398396
prog="incremental_checker", description=__doc__, formatter_class=help_factory
399397
)

misc/perf_checker.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import subprocess
99
import textwrap
1010
import time
11-
from typing import Callable, List, Tuple
11+
from typing import Callable, Tuple
1212

1313

1414
class Command:
@@ -28,7 +28,7 @@ def delete_folder(folder_path: str) -> None:
2828
shutil.rmtree(folder_path)
2929

3030

31-
def execute(command: List[str]) -> None:
31+
def execute(command: list[str]) -> None:
3232
proc = subprocess.Popen(
3333
" ".join(command), stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True
3434
)
@@ -45,7 +45,7 @@ def execute(command: List[str]) -> None:
4545
raise RuntimeError("Unexpected error from external tool.")
4646

4747

48-
def trial(num_trials: int, command: Command) -> List[float]:
48+
def trial(num_trials: int, command: Command) -> list[float]:
4949
trials = []
5050
for i in range(num_trials):
5151
command.setup()
@@ -56,7 +56,7 @@ def trial(num_trials: int, command: Command) -> List[float]:
5656
return trials
5757

5858

59-
def report(name: str, times: List[float]) -> None:
59+
def report(name: str, times: list[float]) -> None:
6060
print(f"{name}:")
6161
print(f" Times: {times}")
6262
print(f" Mean: {statistics.mean(times)}")

misc/proper_plugin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from __future__ import annotations
22

3-
from typing import Callable, Optional, Type as typing_Type
3+
from typing import Callable, Type as typing_Type
44

55
from mypy.nodes import TypeInfo
66
from mypy.plugin import FunctionContext, Plugin
@@ -33,7 +33,7 @@ class ProperTypePlugin(Plugin):
3333
all these became dangerous because typ may be e.g. an alias to union.
3434
"""
3535

36-
def get_function_hook(self, fullname: str) -> Optional[Callable[[FunctionContext], Type]]:
36+
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
3737
if fullname == "builtins.isinstance":
3838
return isinstance_proper_hook
3939
if fullname == "mypy.types.get_proper_type":

misc/sync-typeshed.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
import sys
1717
import tempfile
1818
import textwrap
19-
from typing import Optional
2019

2120

2221
def check_state() -> None:
@@ -28,7 +27,7 @@ def check_state() -> None:
2827
sys.exit('error: Output of "git status -s mypy/typeshed" must be empty')
2928

3029

31-
def update_typeshed(typeshed_dir: str, commit: Optional[str]) -> str:
30+
def update_typeshed(typeshed_dir: str, commit: str | None) -> str:
3231
"""Update contents of local typeshed copy.
3332
3433
Return the normalized typeshed commit hash.

misc/test_case_to_actual.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33
import os
44
import os.path
55
import sys
6-
from typing import Iterator, List
6+
from typing import Iterator
77

88

99
class Chunk:
1010
def __init__(self, header_type: str, args: str) -> None:
1111
self.header_type = header_type
1212
self.args = args
13-
self.lines = [] # type: List[str]
13+
self.lines: list[str] = []
1414

1515

1616
def is_header(line: str) -> bool:
@@ -22,7 +22,7 @@ def normalize(lines: Iterator[str]) -> Iterator[str]:
2222

2323

2424
def produce_chunks(lines: Iterator[str]) -> Iterator[Chunk]:
25-
current_chunk = None # type: Chunk
25+
current_chunk: Chunk = None
2626
for line in normalize(lines):
2727
if is_header(line):
2828
if current_chunk is not None:
@@ -36,7 +36,7 @@ def produce_chunks(lines: Iterator[str]) -> Iterator[Chunk]:
3636
yield current_chunk
3737

3838

39-
def write_out(filename: str, lines: List[str]) -> None:
39+
def write_out(filename: str, lines: list[str]) -> None:
4040
os.makedirs(os.path.dirname(filename), exist_ok=True)
4141
with open(filename, "w") as stream:
4242
stream.write("\n".join(lines))

0 commit comments

Comments
 (0)