Skip to content

Commit 42d86c4

Browse files
authored
Run pyupgrade 2.31.0. (#10141)
This PR runs [pyupgrade](https://github.com/asottile/pyupgrade) to modernize some syntax in the Python code base. (I am preparing a "better code" talk for our team that will reference this PR.) The kinds of modernizing changes that pyupgrade makes are similar in purpose to those made by clang-tidy (#9860), but for Python. These include things like: - Using literals for empty dicts `{}` and lists `[]`, because they are a bit faster and more readable than `dict()` or `list()` - Removing extra parentheses or braces wrapping generator expressions if not needed - Preferring format strings - Using canonical error names, e.g. `IOError` became an alias for `OSError` in Python 3.3. - Replacing the "new-style" class definitions like `class A(object):` with the simpler syntax `class A:` - Removing unnecessary `__future__` imports that were needed for Python 2 compatibility, like `print_function` and `division` - Using raw strings for regular expressions, to clarify intent and avoid extra escaping The [pyupgrade README](https://github.com/asottile/pyupgrade) has a long showcase of other rules. Notes for reviewers: - pyupgrade has a lot of opinions on how to use type annotations, and I'm not sure if I like all of them (some may have compatibility issues?). I have skipped over the type annotations for now, to set a more reasonable scope for this PR. See commit 54b16b9 (since reverted) for examples. Please let me know what you think about these changes and I may investigate them further in a follow-up PR! - I have not added this tool to our CI style checks via a pre-commit hook yet. That can be done in a follow-up PR if we agree that we would like these types of changes to be required in the future. - I used the argument `--py37-plus` to only perform changes that are compatible with Python 3.7+. - I can revert the changes to the vendored code in `versioneer.py` if desired. (It's pretty outdated anyway, it looks like we're using versioneer 0.18, released on January 1, 2017.) Authors: - Bradley Dice (https://github.com/bdice) Approvers: - Vyas Ramasubramani (https://github.com/vyasr) - Charles Blackmon-Luca (https://github.com/charlesbluca) - AJ Schmidt (https://github.com/ajschmidt8) URL: #10141
1 parent 1754731 commit 42d86c4

Some content is hidden

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

53 files changed

+186
-248
lines changed

ci/utils/nbtestlog2junitxml.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
from enum import Enum
88

99

10-
startingPatt = re.compile("^STARTING: ([\w\.\-]+)$")
11-
skippingPatt = re.compile("^SKIPPING: ([\w\.\-]+)\s*(\(([\w\.\-\ \,]+)\))?\s*$")
12-
exitCodePatt = re.compile("^EXIT CODE: (\d+)$")
13-
folderPatt = re.compile("^FOLDER: ([\w\.\-]+)$")
14-
timePatt = re.compile("^real\s+([\d\.ms]+)$")
10+
startingPatt = re.compile(r"^STARTING: ([\w\.\-]+)$")
11+
skippingPatt = re.compile(r"^SKIPPING: ([\w\.\-]+)\s*(\(([\w\.\-\ \,]+)\))?\s*$")
12+
exitCodePatt = re.compile(r"^EXIT CODE: (\d+)$")
13+
folderPatt = re.compile(r"^FOLDER: ([\w\.\-]+)$")
14+
timePatt = re.compile(r"^real\s+([\d\.ms]+)$")
1515
linePatt = re.compile("^" + ("-" * 80) + "$")
1616

1717

cpp/scripts/run-clang-format.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
# limitations under the License.
1414
#
1515

16-
from __future__ import print_function
1716

1817
import argparse
1918
import os
@@ -124,19 +123,19 @@ def run_clang_format(src, dst, exe, verbose, inplace):
124123
os.makedirs(dstdir)
125124
# run the clang format command itself
126125
if src == dst:
127-
cmd = "%s -i %s" % (exe, src)
126+
cmd = f"{exe} -i {src}"
128127
else:
129-
cmd = "%s %s > %s" % (exe, src, dst)
128+
cmd = f"{exe} {src} > {dst}"
130129
try:
131130
subprocess.check_call(cmd, shell=True)
132131
except subprocess.CalledProcessError:
133132
print("Failed to run clang-format! Maybe your env is not proper?")
134133
raise
135134
# run the diff to check if there are any formatting issues
136135
if inplace:
137-
cmd = "diff -q %s %s >/dev/null" % (src, dst)
136+
cmd = f"diff -q {src} {dst} >/dev/null"
138137
else:
139-
cmd = "diff %s %s" % (src, dst)
138+
cmd = f"diff {src} {dst}"
140139

141140
try:
142141
subprocess.check_call(cmd, shell=True)

cpp/scripts/run-clang-tidy.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
# limitations under the License.
1414
#
1515

16-
from __future__ import print_function
1716
import re
1817
import os
1918
import subprocess
@@ -67,7 +66,7 @@ def parse_args():
6766

6867

6968
def get_all_commands(cdb):
70-
with open(cdb, "r") as fp:
69+
with open(cdb) as fp:
7170
return json.load(fp)
7271

7372

@@ -195,10 +194,10 @@ def collect_result(result):
195194

196195
def print_result(passed, stdout, file):
197196
status_str = "PASSED" if passed else "FAILED"
198-
print("%s File:%s %s %s" % (SEPARATOR, file, status_str, SEPARATOR))
197+
print(f"{SEPARATOR} File:{file} {status_str} {SEPARATOR}")
199198
if stdout:
200199
print(stdout)
201-
print("%s File:%s ENDS %s" % (SEPARATOR, file, SEPARATOR))
200+
print(f"{SEPARATOR} File:{file} ENDS {SEPARATOR}")
202201

203202

204203
def print_results():

cpp/scripts/sort_ninja_log.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333

3434
# build a map of the log entries
3535
entries = {}
36-
with open(log_file, "r") as log:
36+
with open(log_file) as log:
3737
last = 0
3838
files = {}
3939
for line in log:

docs/cudf/source/conf.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
#!/usr/bin/env python3
2-
# -*- coding: utf-8 -*-
3-
#
42
# Copyright (c) 2018-2021, NVIDIA CORPORATION.
53
#
64
# cudf documentation build configuration file, created by

python/cudf/cudf/_fuzz_testing/fuzzer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
)
1515

1616

17-
class Fuzzer(object):
17+
class Fuzzer:
1818
def __init__(
1919
self,
2020
target,

python/cudf/cudf/_fuzz_testing/io.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
)
1717

1818

19-
class IOFuzz(object):
19+
class IOFuzz:
2020
def __init__(
2121
self,
2222
dirs=None,
@@ -59,7 +59,7 @@ def __init__(
5959
self._current_buffer = None
6060

6161
def _load_params(self, path):
62-
with open(path, "r") as f:
62+
with open(path) as f:
6363
params = json.load(f)
6464
self._inputs.append(params)
6565

python/cudf/cudf/_fuzz_testing/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from cudf._fuzz_testing import fuzzer
44

55

6-
class PythonFuzz(object):
6+
class PythonFuzz:
77
def __init__(self, func, params=None, data_handle=None, **kwargs):
88
self.function = func
99
self.data_handler_class = data_handle

python/cudf/cudf/_version.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def run_command(
8686
stderr=(subprocess.PIPE if hide_stderr else None),
8787
)
8888
break
89-
except EnvironmentError:
89+
except OSError:
9090
e = sys.exc_info()[1]
9191
if e.errno == errno.ENOENT:
9292
continue
@@ -96,7 +96,7 @@ def run_command(
9696
return None, None
9797
else:
9898
if verbose:
99-
print("unable to find command, tried %s" % (commands,))
99+
print(f"unable to find command, tried {commands}")
100100
return None, None
101101
stdout = p.communicate()[0].strip()
102102
if sys.version_info[0] >= 3:
@@ -149,7 +149,7 @@ def git_get_keywords(versionfile_abs):
149149
# _version.py.
150150
keywords = {}
151151
try:
152-
f = open(versionfile_abs, "r")
152+
f = open(versionfile_abs)
153153
for line in f.readlines():
154154
if line.strip().startswith("git_refnames ="):
155155
mo = re.search(r'=\s*"(.*)"', line)
@@ -164,7 +164,7 @@ def git_get_keywords(versionfile_abs):
164164
if mo:
165165
keywords["date"] = mo.group(1)
166166
f.close()
167-
except EnvironmentError:
167+
except OSError:
168168
pass
169169
return keywords
170170

@@ -188,11 +188,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
188188
if verbose:
189189
print("keywords are unexpanded, not using")
190190
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
191-
refs = set([r.strip() for r in refnames.strip("()").split(",")])
191+
refs = {r.strip() for r in refnames.strip("()").split(",")}
192192
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
193193
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
194194
TAG = "tag: "
195-
tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)])
195+
tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
196196
if not tags:
197197
# Either we're using git < 1.8.3, or there really are no tags. We use
198198
# a heuristic: assume all version tags have a digit. The old git %d
@@ -201,7 +201,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
201201
# between branches and tags. By ignoring refnames without digits, we
202202
# filter out many common branch names like "release" and
203203
# "stabilization", as well as "HEAD" and "master".
204-
tags = set([r for r in refs if re.search(r"\d", r)])
204+
tags = {r for r in refs if re.search(r"\d", r)}
205205
if verbose:
206206
print("discarding '%s', no digits" % ",".join(refs - tags))
207207
if verbose:
@@ -308,10 +308,9 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
308308
if verbose:
309309
fmt = "tag '%s' doesn't start with prefix '%s'"
310310
print(fmt % (full_tag, tag_prefix))
311-
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
312-
full_tag,
313-
tag_prefix,
314-
)
311+
pieces[
312+
"error"
313+
] = f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'"
315314
return pieces
316315
pieces["closest-tag"] = full_tag[len(tag_prefix) :]
317316

python/cudf/cudf/comm/gpuarrow.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def to_dict(self):
5858
return dc
5959

6060

61-
class GpuArrowNodeReader(object):
61+
class GpuArrowNodeReader:
6262
def __init__(self, table, index):
6363
self._table = table
6464
self._field = table.schema[index]

0 commit comments

Comments
 (0)