Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 57e57fa

Browse files
authored
misc: run pyupgrade (#12709)
Re-attempt of #10741 Ran: `pyupgrade --py36-plus $(fd -e py) --keep-runtime-typing` I mostly only needed to change things where NamedTuple comments got dropped. Co-authored-by: hauntsaninja <>
1 parent 1662fe8 commit 57e57fa

13 files changed

Lines changed: 68 additions & 69 deletions

misc/actions_stubs.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,15 @@ def apply_all(func: Any, directory: str, extension: str,
1515
to_extension: str='', exclude: Tuple[str]=('',),
1616
recursive: bool=True, debug: bool=False) -> None:
1717
excluded = [x+extension for x in exclude] if exclude else []
18-
for p, d, files in os.walk(os.path.join(base_path,directory)):
18+
for p, d, files in os.walk(os.path.join(base_path, directory)):
1919
for f in files:
20-
if "{}".format(f) in excluded:
20+
if f in excluded:
2121
continue
22-
inner_path = os.path.join(p,f)
22+
inner_path = os.path.join(p, f)
2323
if not inner_path.endswith(extension):
2424
continue
2525
if to_extension:
26-
new_path = "{}{}".format(inner_path[:-len(extension)],to_extension)
26+
new_path = f"{inner_path[:-len(extension)]}{to_extension}"
2727
func(inner_path,new_path)
2828
else:
2929
func(inner_path)
@@ -91,9 +91,9 @@ def main(action: str, directory: str, extension: str, to_extension: str,
9191

9292
rec = "[Recursively] " if not_recursive else ''
9393
if not extension.startswith('.'):
94-
extension = ".{}".format(extension)
94+
extension = f".{extension}"
9595
if not to_extension.startswith('.'):
96-
to_extension = ".{}".format(to_extension)
96+
to_extension = f".{to_extension}"
9797
if directory.endswith('/'):
9898
directory = directory[:-1]
9999
if action == 'cp':

misc/analyze_cache.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@ def extract(chunks: Iterable[JsonDict]) -> Iterable[JsonDict]:
3737

3838

3939
def load_json(data_path: str, meta_path: str) -> CacheData:
40-
with open(data_path, 'r') as ds:
40+
with open(data_path) as ds:
4141
data_json = json.load(ds)
4242

43-
with open(meta_path, 'r') as ms:
43+
with open(meta_path) as ms:
4444
meta_json = json.load(ms)
4545

4646
data_size = os.path.getsize(data_path)
@@ -66,7 +66,7 @@ def pluck(name: str, chunks: Iterable[JsonDict]) -> Iterable[JsonDict]:
6666

6767
def report_counter(counter: Counter, amount: Optional[int] = None) -> None:
6868
for name, count in counter.most_common(amount):
69-
print(' {: <8} {}'.format(count, name))
69+
print(f' {count: <8} {name}')
7070
print()
7171

7272

@@ -138,7 +138,7 @@ def main() -> None:
138138
class_chunks = list(extract_classes(json_chunks))
139139

140140
total_size = sum(chunk.total_size for chunk in json_chunks)
141-
print("Total cache size: {:.3f} megabytes".format(total_size / (1024 * 1024)))
141+
print(f"Total cache size: {total_size / (1024 * 1024):.3f} megabytes")
142142
print()
143143

144144
class_name_counter = Counter(chunk[".class"] for chunk in class_chunks)
@@ -154,15 +154,15 @@ def main() -> None:
154154
build = chunk
155155
break
156156
original = json.dumps(build.data, sort_keys=True)
157-
print("Size of build.data.json, in kilobytes: {:.3f}".format(len(original) / 1024))
157+
print(f"Size of build.data.json, in kilobytes: {len(original) / 1024:.3f}")
158158

159159
build.data = compress(build.data)
160160
compressed = json.dumps(build.data, sort_keys=True)
161-
print("Size of compressed build.data.json, in kilobytes: {:.3f}".format(len(compressed) / 1024))
161+
print(f"Size of compressed build.data.json, in kilobytes: {len(compressed) / 1024:.3f}")
162162

163163
build.data = decompress(build.data)
164164
decompressed = json.dumps(build.data, sort_keys=True)
165-
print("Size of decompressed build.data.json, in kilobytes: {:.3f}".format(len(decompressed) / 1024))
165+
print(f"Size of decompressed build.data.json, in kilobytes: {len(decompressed) / 1024:.3f}")
166166

167167
print("Lossless conversion back", original == decompressed)
168168

misc/apply-cache-diff.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def make_cache(input_dir: str, sqlite: bool) -> MetadataStore:
2424

2525
def apply_diff(cache_dir: str, diff_file: str, sqlite: bool = False) -> None:
2626
cache = make_cache(cache_dir, sqlite)
27-
with open(diff_file, "r") as f:
27+
with open(diff_file) as f:
2828
diff = json.load(f)
2929

3030
old_deps = json.loads(cache.read("@deps.meta.json"))

misc/fix_annotate.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ def foo(self, bar, baz=12):
2727
Finally, it knows that __init__() is supposed to return None.
2828
"""
2929

30-
from __future__ import print_function
3130

3231
import os
3332
import re
@@ -90,7 +89,7 @@ def transform(self, node, results):
9089
# Insert '# type: {annot}' comment.
9190
# For reference, see lib2to3/fixes/fix_tuple_params.py in stdlib.
9291
if len(children) >= 2 and children[1].type == token.INDENT:
93-
children[1].prefix = '%s# type: %s\n%s' % (children[1].value, annot, children[1].prefix)
92+
children[1].prefix = '{}# type: {}\n{}'.format(children[1].value, annot, children[1].prefix)
9493
children[1].changed()
9594
if FixAnnotate.counter is not None:
9695
FixAnnotate.counter -= 1

misc/incremental_checker.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,10 @@ def ensure_environment_is_ready(mypy_path: str, temp_repo_path: str, mypy_cache_
9292

9393

9494
def initialize_repo(repo_url: str, temp_repo_path: str, branch: str) -> None:
95-
print("Cloning repo {0} to {1}".format(repo_url, temp_repo_path))
95+
print(f"Cloning repo {repo_url} to {temp_repo_path}")
9696
execute(["git", "clone", repo_url, temp_repo_path])
9797
if branch is not None:
98-
print("Checking out branch {}".format(branch))
98+
print(f"Checking out branch {branch}")
9999
execute(["git", "-C", temp_repo_path, "checkout", branch])
100100

101101

@@ -110,13 +110,13 @@ def get_commits(repo_folder_path: str, commit_range: str) -> List[Tuple[str, str
110110

111111

112112
def get_commits_starting_at(repo_folder_path: str, start_commit: str) -> List[Tuple[str, str]]:
113-
print("Fetching commits starting at {0}".format(start_commit))
114-
return get_commits(repo_folder_path, '{0}^..HEAD'.format(start_commit))
113+
print(f"Fetching commits starting at {start_commit}")
114+
return get_commits(repo_folder_path, f'{start_commit}^..HEAD')
115115

116116

117117
def get_nth_commit(repo_folder_path: str, n: int) -> Tuple[str, str]:
118-
print("Fetching last {} commits (or all, if there are fewer commits than n)".format(n))
119-
return get_commits(repo_folder_path, '-{}'.format(n))[0]
118+
print(f"Fetching last {n} commits (or all, if there are fewer commits than n)")
119+
return get_commits(repo_folder_path, f'-{n}')[0]
120120

121121

122122
def run_mypy(target_file_path: Optional[str],
@@ -187,7 +187,7 @@ def stop_daemon() -> None:
187187

188188
def load_cache(incremental_cache_path: str = CACHE_PATH) -> JsonDict:
189189
if os.path.exists(incremental_cache_path):
190-
with open(incremental_cache_path, 'r') as stream:
190+
with open(incremental_cache_path) as stream:
191191
return json.load(stream)
192192
else:
193193
return {}
@@ -213,17 +213,17 @@ def set_expected(commits: List[Tuple[str, str]],
213213
skip evaluating that commit and move on to the next."""
214214
for commit_id, message in commits:
215215
if commit_id in cache:
216-
print('Skipping commit (already cached): {0}: "{1}"'.format(commit_id, message))
216+
print(f'Skipping commit (already cached): {commit_id}: "{message}"')
217217
else:
218-
print('Caching expected output for commit {0}: "{1}"'.format(commit_id, message))
218+
print(f'Caching expected output for commit {commit_id}: "{message}"')
219219
execute(["git", "-C", temp_repo_path, "checkout", commit_id])
220220
runtime, output, stats = run_mypy(target_file_path, mypy_cache_path, mypy_script,
221221
incremental=False)
222222
cache[commit_id] = {'runtime': runtime, 'output': output}
223223
if output == "":
224-
print(" Clean output ({:.3f} sec)".format(runtime))
224+
print(f" Clean output ({runtime:.3f} sec)")
225225
else:
226-
print(" Output ({:.3f} sec)".format(runtime))
226+
print(f" Output ({runtime:.3f} sec)")
227227
print_offset(output, 8)
228228
print()
229229

@@ -246,7 +246,7 @@ def test_incremental(commits: List[Tuple[str, str]],
246246
commits = [commits[0]] + commits
247247
overall_stats = {} # type: Dict[str, float]
248248
for commit_id, message in commits:
249-
print('Now testing commit {0}: "{1}"'.format(commit_id, message))
249+
print(f'Now testing commit {commit_id}: "{message}"')
250250
execute(["git", "-C", temp_repo_path, "checkout", commit_id])
251251
runtime, output, stats = run_mypy(target_file_path, mypy_cache_path, mypy_script,
252252
incremental=True, daemon=daemon)
@@ -255,18 +255,18 @@ def test_incremental(commits: List[Tuple[str, str]],
255255
expected_output = cache[commit_id]['output'] # type: str
256256
if output != expected_output:
257257
print(" Output does not match expected result!")
258-
print(" Expected output ({:.3f} sec):".format(expected_runtime))
258+
print(f" Expected output ({expected_runtime:.3f} sec):")
259259
print_offset(expected_output, 8)
260-
print(" Actual output: ({:.3f} sec):".format(runtime))
260+
print(f" Actual output: ({runtime:.3f} sec):")
261261
print_offset(output, 8)
262262
if exit_on_error:
263263
break
264264
else:
265265
print(" Output matches expected result!")
266-
print(" Incremental: {:.3f} sec".format(runtime))
267-
print(" Original: {:.3f} sec".format(expected_runtime))
266+
print(f" Incremental: {runtime:.3f} sec")
267+
print(f" Original: {expected_runtime:.3f} sec")
268268
if relevant_stats:
269-
print(" Stats: {}".format(relevant_stats))
269+
print(f" Stats: {relevant_stats}")
270270
if overall_stats:
271271
print("Overall stats:", overall_stats)
272272

@@ -324,7 +324,7 @@ def test_repo(target_repo_url: str, temp_repo_path: str,
324324
elif range_type == "commit":
325325
start_commit = range_start
326326
else:
327-
raise RuntimeError("Invalid option: {}".format(range_type))
327+
raise RuntimeError(f"Invalid option: {range_type}")
328328
commits = get_commits_starting_at(temp_repo_path, start_commit)
329329
if params.limit:
330330
commits = commits[:params.limit]
@@ -419,10 +419,10 @@ def main() -> None:
419419
# The path to store the mypy incremental mode cache data
420420
mypy_cache_path = os.path.abspath(os.path.join(mypy_path, "misc", ".mypy_cache"))
421421

422-
print("Assuming mypy is located at {0}".format(mypy_path))
423-
print("Temp repo will be cloned at {0}".format(temp_repo_path))
424-
print("Testing file/dir located at {0}".format(target_file_path))
425-
print("Using cache data located at {0}".format(incremental_cache_path))
422+
print(f"Assuming mypy is located at {mypy_path}")
423+
print(f"Temp repo will be cloned at {temp_repo_path}")
424+
print(f"Testing file/dir located at {target_file_path}")
425+
print(f"Using cache data located at {incremental_cache_path}")
426426
print()
427427

428428
test_repo(params.repo_url, temp_repo_path, target_file_path,

misc/perf_checker.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,10 @@ def trial(num_trials: int, command: Command) -> List[float]:
5858

5959

6060
def report(name: str, times: List[float]) -> None:
61-
print("{}:".format(name))
62-
print(" Times: {}".format(times))
63-
print(" Mean: {}".format(statistics.mean(times)))
64-
print(" Stdev: {}".format(statistics.stdev(times)))
61+
print(f"{name}:")
62+
print(f" Times: {times}")
63+
print(f" Mean: {statistics.mean(times)}")
64+
print(f" Stdev: {statistics.stdev(times)}")
6565
print()
6666

6767

misc/sync-typeshed.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def main() -> None:
7777
if not args.typeshed_dir:
7878
# Clone typeshed repo if no directory given.
7979
with tempfile.TemporaryDirectory() as tempdir:
80-
print('Cloning typeshed in {}...'.format(tempdir))
80+
print(f'Cloning typeshed in {tempdir}...')
8181
subprocess.run(['git', 'clone', 'https://github.com/python/typeshed.git'],
8282
check=True, cwd=tempdir)
8383
repo = os.path.join(tempdir, 'typeshed')

misc/test_case_to_actual.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def main() -> None:
6262
return
6363

6464
test_file_path, root_path = sys.argv[1], sys.argv[2]
65-
with open(test_file_path, 'r') as stream:
65+
with open(test_file_path) as stream:
6666
chunks = produce_chunks(iter(stream))
6767
write_tree(root_path, chunks)
6868

misc/touch_checker.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def make_change_wrappers(filename: str) -> Tuple[Command, Command]:
6767

6868
def setup() -> None:
6969
nonlocal copy
70-
with open(filename, 'r') as stream:
70+
with open(filename) as stream:
7171
copy = stream.read()
7272
with open(filename, 'a') as stream:
7373
stream.write('\n\nfoo = 3')
@@ -102,48 +102,48 @@ def main() -> None:
102102
lambda: None,
103103
lambda: execute(["python3", "-m", "mypy", "mypy"]),
104104
lambda: None)
105-
print("Baseline: {}".format(baseline))
105+
print(f"Baseline: {baseline}")
106106

107107
cold = test(
108108
lambda: delete_folder(".mypy_cache"),
109109
lambda: execute(["python3", "-m", "mypy", "-i", "mypy"]),
110110
lambda: None)
111-
print("Cold cache: {}".format(cold))
111+
print(f"Cold cache: {cold}")
112112

113113
warm = test(
114114
lambda: None,
115115
lambda: execute(["python3", "-m", "mypy", "-i", "mypy"]),
116116
lambda: None)
117-
print("Warm cache: {}".format(warm))
117+
print(f"Warm cache: {warm}")
118118

119119
print()
120120

121121
deltas = []
122122
for filename in glob.iglob("mypy/**/*.py", recursive=True):
123-
print("{} {}".format(verb, filename))
123+
print(f"{verb} {filename}")
124124

125125
setup, teardown = make_wrappers(filename)
126126
delta = test(
127127
setup,
128128
lambda: execute(["python3", "-m", "mypy", "-i", "mypy"]),
129129
teardown)
130-
print(" Time: {}".format(delta))
130+
print(f" Time: {delta}")
131131
deltas.append(delta)
132132
print()
133133

134134
print("Initial:")
135-
print(" Baseline: {}".format(baseline))
136-
print(" Cold cache: {}".format(cold))
137-
print(" Warm cache: {}".format(warm))
135+
print(f" Baseline: {baseline}")
136+
print(f" Cold cache: {cold}")
137+
print(f" Warm cache: {warm}")
138138
print()
139139
print("Aggregate:")
140-
print(" Times: {}".format(deltas))
141-
print(" Mean: {}".format(statistics.mean(deltas)))
142-
print(" Median: {}".format(statistics.median(deltas)))
143-
print(" Stdev: {}".format(statistics.stdev(deltas)))
144-
print(" Min: {}".format(min(deltas)))
145-
print(" Max: {}".format(max(deltas)))
146-
print(" Total: {}".format(sum(deltas)))
140+
print(f" Times: {deltas}")
141+
print(f" Mean: {statistics.mean(deltas)}")
142+
print(f" Median: {statistics.median(deltas)}")
143+
print(f" Stdev: {statistics.stdev(deltas)}")
144+
print(f" Min: {min(deltas)}")
145+
print(f" Max: {max(deltas)}")
146+
print(f" Total: {sum(deltas)}")
147147
print()
148148

149149
if __name__ == '__main__':

misc/variadics.py

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

99
def prelude(limit: int, bound: str) -> None:
1010
print('from typing import Callable, Iterable, Iterator, Tuple, TypeVar, overload')
11-
print('Ts = TypeVar(\'Ts\', bound={bound})'.format(bound=bound))
12-
print('R = TypeVar(\'R\')')
11+
print(f"Ts = TypeVar('Ts', bound={bound})")
12+
print("R = TypeVar('R')")
1313
for i in range(LIMIT):
1414
print('T{i} = TypeVar(\'T{i}\', bound={bound})'.format(i=i+1, bound=bound))
1515

@@ -19,8 +19,8 @@ def expand_template(template: str,
1919
limit: int = LIMIT) -> None:
2020
print()
2121
for i in range(lower, limit):
22-
tvs = ', '.join('T{i}'.format(i=j+1) for j in range(i))
23-
args = ', '.join(arg_template.format(i=j+1, Ts='T{}'.format(j+1))
22+
tvs = ', '.join(f'T{j+1}' for j in range(i))
23+
args = ', '.join(arg_template.format(i=j+1, Ts=f'T{j+1}')
2424
for j in range(i))
2525
print('@overload')
2626
s = template.format(Ts=tvs, argsTs=args)
@@ -49,6 +49,6 @@ def main():
4949
expand_template('def make_check({argsTs}) -> Callable[[{Ts}], bool]: ...')
5050
expand_template('def my_map(f: Callable[[{Ts}], R], {argsTs}) -> Iterator[R]: ...',
5151
'arg{i}: Iterable[{Ts}]')
52-
52+
5353

5454
main()

0 commit comments

Comments
 (0)