Skip to content

Commit d367a01

Browse files
BordaNicolasHug
andauthored
Use f-strings almost everywhere, and other cleanups by applying pyupgrade (#4585)
Co-authored-by: Nicolas Hug <[email protected]>
1 parent 50dfe20 commit d367a01

File tree

136 files changed

+694
-767
lines changed

Some content is hidden

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

136 files changed

+694
-767
lines changed

.circleci/unittest/linux/scripts/run-clang-format.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
import argparse
3535
import difflib
3636
import fnmatch
37-
import io
3837
import multiprocessing
3938
import os
4039
import signal
@@ -87,20 +86,20 @@ def list_files(files, recursive=False, extensions=None, exclude=None):
8786
def make_diff(file, original, reformatted):
8887
return list(
8988
difflib.unified_diff(
90-
original, reformatted, fromfile="{}\t(original)".format(file), tofile="{}\t(reformatted)".format(file), n=3
89+
original, reformatted, fromfile=f"{file}\t(original)", tofile=f"{file}\t(reformatted)", n=3
9190
)
9291
)
9392

9493

9594
class DiffError(Exception):
9695
def __init__(self, message, errs=None):
97-
super(DiffError, self).__init__(message)
96+
super().__init__(message)
9897
self.errs = errs or []
9998

10099

101100
class UnexpectedError(Exception):
102101
def __init__(self, message, exc=None):
103-
super(UnexpectedError, self).__init__(message)
102+
super().__init__(message)
104103
self.formatted_traceback = traceback.format_exc()
105104
self.exc = exc
106105

@@ -112,14 +111,14 @@ def run_clang_format_diff_wrapper(args, file):
112111
except DiffError:
113112
raise
114113
except Exception as e:
115-
raise UnexpectedError("{}: {}: {}".format(file, e.__class__.__name__, e), e)
114+
raise UnexpectedError(f"{file}: {e.__class__.__name__}: {e}", e)
116115

117116

118117
def run_clang_format_diff(args, file):
119118
try:
120-
with io.open(file, "r", encoding="utf-8") as f:
119+
with open(file, encoding="utf-8") as f:
121120
original = f.readlines()
122-
except IOError as exc:
121+
except OSError as exc:
123122
raise DiffError(str(exc))
124123
invocation = [args.clang_format_executable, file]
125124

@@ -145,7 +144,7 @@ def run_clang_format_diff(args, file):
145144
invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, encoding="utf-8"
146145
)
147146
except OSError as exc:
148-
raise DiffError("Command '{}' failed to start: {}".format(subprocess.list2cmdline(invocation), exc))
147+
raise DiffError(f"Command '{subprocess.list2cmdline(invocation)}' failed to start: {exc}")
149148
proc_stdout = proc.stdout
150149
proc_stderr = proc.stderr
151150

@@ -203,7 +202,7 @@ def print_trouble(prog, message, use_colors):
203202
error_text = "error:"
204203
if use_colors:
205204
error_text = bold_red(error_text)
206-
print("{}: {} {}".format(prog, error_text, message), file=sys.stderr)
205+
print(f"{prog}: {error_text} {message}", file=sys.stderr)
207206

208207

209208
def main():
@@ -216,7 +215,7 @@ def main():
216215
)
217216
parser.add_argument(
218217
"--extensions",
219-
help="comma separated list of file extensions (default: {})".format(DEFAULT_EXTENSIONS),
218+
help=f"comma separated list of file extensions (default: {DEFAULT_EXTENSIONS})",
220219
default=DEFAULT_EXTENSIONS,
221220
)
222221
parser.add_argument("-r", "--recursive", action="store_true", help="run recursively over directories")
@@ -227,7 +226,7 @@ def main():
227226
metavar="N",
228227
type=int,
229228
default=0,
230-
help="run N clang-format jobs in parallel" " (default number of cpus + 1)",
229+
help="run N clang-format jobs in parallel (default number of cpus + 1)",
231230
)
232231
parser.add_argument(
233232
"--color", default="auto", choices=["auto", "always", "never"], help="show colored diff (default: auto)"
@@ -238,7 +237,7 @@ def main():
238237
metavar="PATTERN",
239238
action="append",
240239
default=[],
241-
help="exclude paths matching the given glob-like pattern(s)" " from recursive search",
240+
help="exclude paths matching the given glob-like pattern(s) from recursive search",
242241
)
243242

244243
args = parser.parse_args()
@@ -263,7 +262,7 @@ def main():
263262
colored_stdout = sys.stdout.isatty()
264263
colored_stderr = sys.stderr.isatty()
265264

266-
version_invocation = [args.clang_format_executable, str("--version")]
265+
version_invocation = [args.clang_format_executable, "--version"]
267266
try:
268267
subprocess.check_call(version_invocation, stdout=DEVNULL)
269268
except subprocess.CalledProcessError as e:
@@ -272,7 +271,7 @@ def main():
272271
except OSError as e:
273272
print_trouble(
274273
parser.prog,
275-
"Command '{}' failed to start: {}".format(subprocess.list2cmdline(version_invocation), e),
274+
f"Command '{subprocess.list2cmdline(version_invocation)}' failed to start: {e}",
276275
use_colors=colored_stderr,
277276
)
278277
return ExitStatus.TROUBLE

.pre-commit-config.yaml

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,30 @@
11
repos:
2+
- repo: https://github.com/pre-commit/pre-commit-hooks
3+
rev: v4.0.1
4+
hooks:
5+
- id: check-docstring-first
6+
- id: check-toml
7+
- id: check-yaml
8+
exclude: packaging/.*
9+
- id: end-of-file-fixer
10+
11+
# - repo: https://github.com/asottile/pyupgrade
12+
# rev: v2.29.0
13+
# hooks:
14+
# - id: pyupgrade
15+
# args: [--py36-plus]
16+
# name: Upgrade code
17+
218
- repo: https://github.com/omnilib/ufmt
319
rev: v1.3.0
420
hooks:
521
- id: ufmt
622
additional_dependencies:
723
- black == 21.9b0
824
- usort == 0.6.4
25+
926
- repo: https://gitlab.com/pycqa/flake8
1027
rev: 3.9.2
1128
hooks:
1229
- id: flake8
1330
args: [--config=setup.cfg]
14-
- repo: https://github.com/pre-commit/pre-commit-hooks
15-
rev: v4.0.1
16-
hooks:
17-
- id: check-docstring-first
18-
- id: check-toml
19-
- id: check-yaml
20-
exclude: packaging/.*
21-
- id: end-of-file-fixer

docs/source/conf.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python3
2-
# -*- coding: utf-8 -*-
32
#
43
# PyTorch documentation build configuration file, created by
54
# sphinx-quickstart on Fri Dec 23 13:31:47 2016.

gallery/plot_scripted_tensor_transforms.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def forward(self, x: torch.Tensor) -> torch.Tensor:
125125

126126
import json
127127

128-
with open(Path('assets') / 'imagenet_class_index.json', 'r') as labels_file:
128+
with open(Path('assets') / 'imagenet_class_index.json') as labels_file:
129129
labels = json.load(labels_file)
130130

131131
for i, (pred, pred_scripted) in enumerate(zip(res, res_scripted)):

gallery/plot_video_api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def example_read_video(video_object, start=0, end=None, read_video=True, read_au
137137
if end < start:
138138
raise ValueError(
139139
"end time should be larger than start time, got "
140-
"start time={} and end time={}".format(start, end)
140+
f"start time={start} and end time={end}"
141141
)
142142

143143
video_frames = torch.empty(0)

packaging/wheel/relocate.py

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
31
"""Helper script to package wheels and relocate binaries."""
42

53
import glob
@@ -157,7 +155,7 @@ def relocate_elf_library(patchelf, output_dir, output_library, binary):
157155
rename and copy them into the wheel while updating their respective rpaths.
158156
"""
159157

160-
print("Relocating {0}".format(binary))
158+
print(f"Relocating {binary}")
161159
binary_path = osp.join(output_library, binary)
162160

163161
ld_tree = lddtree(binary_path)
@@ -173,12 +171,12 @@ def relocate_elf_library(patchelf, output_dir, output_library, binary):
173171
print(library)
174172

175173
if library_info["path"] is None:
176-
print("Omitting {0}".format(library))
174+
print(f"Omitting {library}")
177175
continue
178176

179177
if library in ALLOWLIST:
180178
# Omit glibc/gcc/system libraries
181-
print("Omitting {0}".format(library))
179+
print(f"Omitting {library}")
182180
continue
183181

184182
parent_dependencies = binary_dependencies.get(parent, [])
@@ -201,7 +199,7 @@ def relocate_elf_library(patchelf, output_dir, output_library, binary):
201199
if library != binary:
202200
library_path = binary_paths[library]
203201
new_library_path = patch_new_path(library_path, new_libraries_path)
204-
print("{0} -> {1}".format(library, new_library_path))
202+
print(f"{library} -> {new_library_path}")
205203
shutil.copyfile(library_path, new_library_path)
206204
new_names[library] = new_library_path
207205

@@ -214,7 +212,7 @@ def relocate_elf_library(patchelf, output_dir, output_library, binary):
214212
new_library_name = new_names[library]
215213
for dep in library_dependencies:
216214
new_dep = osp.basename(new_names[dep])
217-
print("{0}: {1} -> {2}".format(library, dep, new_dep))
215+
print(f"{library}: {dep} -> {new_dep}")
218216
subprocess.check_output(
219217
[patchelf, "--replace-needed", dep, new_dep, new_library_name], cwd=new_libraries_path
220218
)
@@ -228,7 +226,7 @@ def relocate_elf_library(patchelf, output_dir, output_library, binary):
228226
library_dependencies = binary_dependencies[binary]
229227
for dep in library_dependencies:
230228
new_dep = osp.basename(new_names[dep])
231-
print("{0}: {1} -> {2}".format(binary, dep, new_dep))
229+
print(f"{binary}: {dep} -> {new_dep}")
232230
subprocess.check_output([patchelf, "--replace-needed", dep, new_dep, binary], cwd=output_library)
233231

234232
print("Update library rpath")
@@ -244,7 +242,7 @@ def relocate_dll_library(dumpbin, output_dir, output_library, binary):
244242
Given a shared library, find the transitive closure of its dependencies,
245243
rename and copy them into the wheel.
246244
"""
247-
print("Relocating {0}".format(binary))
245+
print(f"Relocating {binary}")
248246
binary_path = osp.join(output_library, binary)
249247

250248
library_dlls = find_dll_dependencies(dumpbin, binary_path)
@@ -255,18 +253,18 @@ def relocate_dll_library(dumpbin, output_dir, output_library, binary):
255253
while binary_queue != []:
256254
library, parent = binary_queue.pop(0)
257255
if library in WINDOWS_ALLOWLIST or library.startswith("api-ms-win"):
258-
print("Omitting {0}".format(library))
256+
print(f"Omitting {library}")
259257
continue
260258

261259
library_path = find_program(library)
262260
if library_path is None:
263-
print("{0} not found".format(library))
261+
print(f"{library} not found")
264262
continue
265263

266264
if osp.basename(osp.dirname(library_path)) == "system32":
267265
continue
268266

269-
print("{0}: {1}".format(library, library_path))
267+
print(f"{library}: {library_path}")
270268
parent_dependencies = binary_dependencies.get(parent, [])
271269
parent_dependencies.append(library)
272270
binary_dependencies[parent] = parent_dependencies
@@ -284,7 +282,7 @@ def relocate_dll_library(dumpbin, output_dir, output_library, binary):
284282
if library != binary:
285283
library_path = binary_paths[library]
286284
new_library_path = osp.join(package_dir, library)
287-
print("{0} -> {1}".format(library, new_library_path))
285+
print(f"{library} -> {new_library_path}")
288286
shutil.copyfile(library_path, new_library_path)
289287

290288

@@ -300,26 +298,24 @@ def compress_wheel(output_dir, wheel, wheel_dir, wheel_name):
300298
full_file = osp.join(root, this_file)
301299
rel_file = osp.relpath(full_file, output_dir)
302300
if full_file == record_file:
303-
f.write("{0},,\n".format(rel_file))
301+
f.write(f"{rel_file},,\n")
304302
else:
305303
digest, size = rehash(full_file)
306-
f.write("{0},{1},{2}\n".format(rel_file, digest, size))
304+
f.write(f"{rel_file},{digest},{size}\n")
307305

308306
print("Compressing wheel")
309307
base_wheel_name = osp.join(wheel_dir, wheel_name)
310308
shutil.make_archive(base_wheel_name, "zip", output_dir)
311309
os.remove(wheel)
312-
shutil.move("{0}.zip".format(base_wheel_name), wheel)
310+
shutil.move(f"{base_wheel_name}.zip", wheel)
313311
shutil.rmtree(output_dir)
314312

315313

316314
def patch_linux():
317315
# Get patchelf location
318316
patchelf = find_program("patchelf")
319317
if patchelf is None:
320-
raise FileNotFoundError(
321-
"Patchelf was not found in the system, please" " make sure that is available on the PATH."
322-
)
318+
raise FileNotFoundError("Patchelf was not found in the system, please make sure that is available on the PATH.")
323319

324320
# Find wheel
325321
print("Finding wheels...")
@@ -338,7 +334,7 @@ def patch_linux():
338334
print("Unzipping wheel...")
339335
wheel_file = osp.basename(wheel)
340336
wheel_dir = osp.dirname(wheel)
341-
print("{0}".format(wheel_file))
337+
print(f"{wheel_file}")
342338
wheel_name, _ = osp.splitext(wheel_file)
343339
unzip_file(wheel, output_dir)
344340

@@ -355,9 +351,7 @@ def patch_win():
355351
# Get dumpbin location
356352
dumpbin = find_program("dumpbin")
357353
if dumpbin is None:
358-
raise FileNotFoundError(
359-
"Dumpbin was not found in the system, please" " make sure that is available on the PATH."
360-
)
354+
raise FileNotFoundError("Dumpbin was not found in the system, please make sure that is available on the PATH.")
361355

362356
# Find wheel
363357
print("Finding wheels...")
@@ -376,7 +370,7 @@ def patch_win():
376370
print("Unzipping wheel...")
377371
wheel_file = osp.basename(wheel)
378372
wheel_dir = osp.dirname(wheel)
379-
print("{0}".format(wheel_file))
373+
print(f"{wheel_file}")
380374
wheel_name, _ = osp.splitext(wheel_file)
381375
unzip_file(wheel, output_dir)
382376

0 commit comments

Comments
 (0)