Skip to content

Commit bfdca5b

Browse files
committed
apply pyupgrade
Signed-off-by: Jirka <[email protected]>
1 parent 453a9c0 commit bfdca5b

Some content is hidden

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

73 files changed

+167
-170
lines changed

.pre-commit-config.yaml

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,13 @@ repos:
2222
args: ['--maxkb=1024']
2323
- id: detect-private-key
2424

25-
#- repo: https://github.com/asottile/pyupgrade
26-
# rev: v2.23.2
27-
# hooks:
28-
# - id: pyupgrade
29-
# args: [--py36-plus]
30-
# name: Upgrade code
25+
- repo: https://github.com/asottile/pyupgrade
26+
rev: v2.27.0
27+
hooks:
28+
- id: pyupgrade
29+
args: [--py36-plus]
30+
name: Upgrade code
31+
exclude: versioneer.py
3132

3233
#- repo: https://github.com/asottile/yesqa
3334
# rev: v1.2.3

monai/_version.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
# This file helps to compute a version number in source trees obtained from
32
# git-archive tarball (such as those provided by githubs download-from-tag
43
# feature). Distribution tarballs (built by setup.py sdist) and build
@@ -81,7 +80,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
8180
stderr=(subprocess.PIPE if hide_stderr
8281
else None))
8382
break
84-
except EnvironmentError:
83+
except OSError:
8584
e = sys.exc_info()[1]
8685
if e.errno == errno.ENOENT:
8786
continue
@@ -91,7 +90,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
9190
return None, None
9291
else:
9392
if verbose:
94-
print("unable to find command, tried %s" % (commands,))
93+
print(f"unable to find command, tried {commands}")
9594
return None, None
9695
stdout = p.communicate()[0].strip().decode()
9796
if p.returncode != 0:
@@ -136,7 +135,7 @@ def git_get_keywords(versionfile_abs):
136135
# _version.py.
137136
keywords = {}
138137
try:
139-
f = open(versionfile_abs, "r")
138+
f = open(versionfile_abs)
140139
for line in f.readlines():
141140
if line.strip().startswith("git_refnames ="):
142141
mo = re.search(r'=\s*"(.*)"', line)
@@ -151,7 +150,7 @@ def git_get_keywords(versionfile_abs):
151150
if mo:
152151
keywords["date"] = mo.group(1)
153152
f.close()
154-
except EnvironmentError:
153+
except OSError:
155154
pass
156155
return keywords
157156

@@ -179,11 +178,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
179178
if verbose:
180179
print("keywords are unexpanded, not using")
181180
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
182-
refs = set([r.strip() for r in refnames.strip("()").split(",")])
181+
refs = {r.strip() for r in refnames.strip("()").split(",")}
183182
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
184183
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
185184
TAG = "tag: "
186-
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
185+
tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
187186
if not tags:
188187
# Either we're using git < 1.8.3, or there really are no tags. We use
189188
# a heuristic: assume all version tags have a digit. The old git %d
@@ -192,7 +191,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
192191
# between branches and tags. By ignoring refnames without digits, we
193192
# filter out many common branch names like "release" and
194193
# "stabilization", as well as "HEAD" and "master".
195-
tags = set([r for r in refs if re.search(r'\d', r)])
194+
tags = {r for r in refs if re.search(r'\d', r)}
196195
if verbose:
197196
print("discarding '%s', no digits" % ",".join(refs - tags))
198197
if verbose:

monai/apps/datasets.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def _generate_data_list(self, dataset_dir: str) -> List[Dict]:
111111
ValueError: When ``section`` is not one of ["training", "validation", "test"].
112112
113113
"""
114-
class_names = sorted((x for x in os.listdir(dataset_dir) if os.path.isdir(os.path.join(dataset_dir, x))))
114+
class_names = sorted(x for x in os.listdir(dataset_dir) if os.path.isdir(os.path.join(dataset_dir, x)))
115115
self.num_class = len(class_names)
116116
image_files = [
117117
[

monai/apps/deepgrow/dataset.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def create_dataset(
9797
image = os.path.abspath(image)
9898
label = os.path.abspath(label) if label else None
9999

100-
logging.info("Image: {}; Label: {}".format(image, label if label else None))
100+
logging.info(f"Image: {image}; Label: {label if label else None}")
101101
data = transforms({image_key: image, label_key: label})
102102
if dimension == 2:
103103
data = _save_data_2d(
@@ -154,7 +154,7 @@ def _save_data_2d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
154154
if vol_label is not None and np.sum(label) == 0:
155155
continue
156156

157-
image_file_prefix = "vol_idx_{:0>4d}_slice_{:0>3d}".format(vol_idx, sid)
157+
image_file_prefix = f"vol_idx_{vol_idx:0>4d}_slice_{sid:0>3d}"
158158
image_file = os.path.join(dataset_dir, "images", image_file_prefix)
159159
image_file += ".npy"
160160

@@ -177,7 +177,7 @@ def _save_data_2d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
177177
unique_labels_count = max(unique_labels_count, len(unique_labels))
178178

179179
for idx in unique_labels:
180-
label_file_prefix = "{}_region_{:0>2d}".format(image_file_prefix, int(idx))
180+
label_file_prefix = f"{image_file_prefix}_region_{int(idx):0>2d}"
181181
label_file = os.path.join(dataset_dir, "labels", label_file_prefix)
182182
label_file += ".npy"
183183

@@ -226,7 +226,7 @@ def _save_data_3d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
226226
label_count = 0
227227
unique_labels_count = 0
228228

229-
image_file_prefix = "vol_idx_{:0>4d}".format(vol_idx)
229+
image_file_prefix = f"vol_idx_{vol_idx:0>4d}"
230230
image_file = os.path.join(dataset_dir, "images", image_file_prefix)
231231
image_file += ".npy"
232232

@@ -248,7 +248,7 @@ def _save_data_3d(vol_idx, vol_image, vol_label, dataset_dir, relative_path):
248248
unique_labels_count = max(unique_labels_count, len(unique_labels))
249249

250250
for idx in unique_labels:
251-
label_file_prefix = "{}_region_{:0>2d}".format(image_file_prefix, int(idx))
251+
label_file_prefix = f"{image_file_prefix}_region_{int(idx):0>2d}"
252252
label_file = os.path.join(dataset_dir, "labels", label_file_prefix)
253253
label_file += ".npy"
254254

monai/apps/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def update_to(self, b: int = 1, bsize: int = 1, tsize: Optional[int] = None):
8181
if not has_tqdm and progress:
8282
warnings.warn("tqdm is not installed, will not show the downloading progress bar.")
8383
urlretrieve(url, filepath)
84-
except (URLError, HTTPError, ContentTooShortError, IOError) as e:
84+
except (URLError, HTTPError, ContentTooShortError, OSError) as e:
8585
print(f"Download failed from {url} to {filepath}.")
8686
raise e
8787

monai/config/deviceconfig.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def get_system_info() -> OrderedDict:
122122
elif output["System"] == "Darwin":
123123
_dict_append(output, "Mac version", lambda: platform.mac_ver()[0])
124124
else:
125-
with open("/etc/os-release", "r") as rel_f:
125+
with open("/etc/os-release") as rel_f:
126126
linux_ver = re.search(r'PRETTY_NAME="(.*)"', rel_f.read())
127127
if linux_ver:
128128
_dict_append(output, "Linux version", lambda: linux_ver.group(1))

monai/data/dataset.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -989,7 +989,7 @@ def __init__(self, datasets: Sequence, transform: Optional[Callable] = None) ->
989989
super().__init__(list(datasets), transform=transform)
990990

991991
def __len__(self) -> int:
992-
return min((len(dataset) for dataset in self.data))
992+
return min(len(dataset) for dataset in self.data)
993993

994994
def _transform(self, index: int):
995995
def to_list(x):

monai/data/dataset_summary.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def __init__(
6060
self.image_key = image_key
6161
self.label_key = label_key
6262
if image_key:
63-
self.meta_key = "{}_{}".format(image_key, meta_key_postfix)
63+
self.meta_key = f"{image_key}_{meta_key_postfix}"
6464
self.all_meta_data: List = []
6565

6666
def collect_meta_data(self):

monai/data/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1029,7 +1029,7 @@ def json_hashing(item) -> bytes:
10291029
"""
10301030
# TODO: Find way to hash transforms content as part of the cache
10311031
cache_key = hashlib.md5(json.dumps(item, sort_keys=True).encode("utf-8")).hexdigest()
1032-
return f"{cache_key}".encode("utf-8")
1032+
return f"{cache_key}".encode()
10331033

10341034

10351035
def pickle_hashing(item, protocol=pickle.HIGHEST_PROTOCOL) -> bytes:
@@ -1044,7 +1044,7 @@ def pickle_hashing(item, protocol=pickle.HIGHEST_PROTOCOL) -> bytes:
10441044
10451045
"""
10461046
cache_key = hashlib.md5(pickle.dumps(sorted_dict(item), protocol=protocol)).hexdigest()
1047-
return f"{cache_key}".encode("utf-8")
1047+
return f"{cache_key}".encode()
10481048

10491049

10501050
def sorted_dict(item, key=None, reverse=False):

monai/losses/deform.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def __init__(
6565
- ``"mean"``: the sum of the output will be divided by the number of elements in the output.
6666
- ``"sum"``: the output will be summed.
6767
"""
68-
super(BendingEnergyLoss, self).__init__(reduction=LossReduction(reduction).value)
68+
super().__init__(reduction=LossReduction(reduction).value)
6969

7070
def forward(self, pred: torch.Tensor) -> torch.Tensor:
7171
"""

0 commit comments

Comments
 (0)