Skip to content

Commit 25469f1

Browse files
authored
Merge pull request #3680 from DimitriPapadopoulos/C4
STY: Apply ruff/flake8-comprehensions rules (C4)
2 parents 6ac81ca + 1747356 commit 25469f1

File tree

22 files changed

+46
-55
lines changed

22 files changed

+46
-55
lines changed

Diff for: nipype/algorithms/modelgen.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def bids_gen_info(
161161
for bids_event_file in bids_event_files:
162162
with open(bids_event_file) as f:
163163
f_events = csv.DictReader(f, skipinitialspace=True, delimiter="\t")
164-
events = [{k: v for k, v in row.items()} for row in f_events]
164+
events = list(f_events)
165165
if not condition_column:
166166
condition_column = "_trial_type"
167167
for i in events:

Diff for: nipype/algorithms/tests/test_CompCor.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -287,9 +287,9 @@ def run_cc(
287287
components_metadata = [
288288
line.rstrip().split("\t") for line in metadata_file
289289
]
290-
components_metadata = {
291-
i: j for i, j in zip(components_metadata[0], components_metadata[1])
292-
}
290+
components_metadata = dict(
291+
zip(components_metadata[0], components_metadata[1])
292+
)
293293
assert components_metadata == expected_metadata
294294

295295
return ccresult

Diff for: nipype/interfaces/ants/segmentation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ def _format_arg(self, opt, spec, val):
194194
priors_paths[0] % i for i in range(1, n_classes + 1)
195195
]
196196

197-
if not all([os.path.exists(p) for p in priors_paths]):
197+
if not all(os.path.exists(p) for p in priors_paths):
198198
raise FileNotFoundError(
199199
"One or more prior images do not exist: "
200200
"%s." % ", ".join(priors_paths)

Diff for: nipype/interfaces/base/core.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,7 @@ def load_inputs_from_json(self, json_file, overwrite=True):
486486
if not overwrite:
487487
def_inputs = list(self.inputs.get_traitsfree().keys())
488488

489-
new_inputs = list(set(list(inputs_dict.keys())) - set(def_inputs))
489+
new_inputs = set(inputs_dict) - set(def_inputs)
490490
for key in new_inputs:
491491
if hasattr(self.inputs, key):
492492
setattr(self.inputs, key, inputs_dict[key])

Diff for: nipype/interfaces/cmtk/cmtk.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ def cmat(
248248
axis=1,
249249
)
250250
)
251-
G.nodes[int(u)]["dn_position"] = tuple([xyz[0], xyz[2], -xyz[1]])
251+
G.nodes[int(u)]["dn_position"] = (xyz[0], xyz[2], -xyz[1])
252252

253253
if intersections:
254254
iflogger.info("Filtering tractography from intersections")
@@ -1070,7 +1070,7 @@ def create_nodes(roi_file, resolution_network_file, out_filename):
10701070
np.where(np.flipud(roiData) == int(d["dn_correspondence_id"])), axis=1
10711071
)
10721072
)
1073-
G.nodes[int(u)]["dn_position"] = tuple([xyz[0], xyz[2], -xyz[1]])
1073+
G.nodes[int(u)]["dn_position"] = (xyz[0], xyz[2], -xyz[1])
10741074
with open(out_filename, 'wb') as f:
10751075
pickle.dump(G, f, pickle.HIGHEST_PROTOCOL)
10761076
return out_filename

Diff for: nipype/interfaces/diffusion_toolkit/dti.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ class DTIRecon(CommandLine):
9797
def _create_gradient_matrix(self, bvecs_file, bvals_file):
9898
_gradient_matrix_file = "gradient_matrix.txt"
9999
with open(bvals_file) as fbvals:
100-
bvals = [val for val in re.split(r"\s+", fbvals.readline().strip())]
100+
bvals = fbvals.readline().strip().split()
101101
with open(bvecs_file) as fbvecs:
102102
bvecs_x = fbvecs.readline().split()
103103
bvecs_y = fbvecs.readline().split()

Diff for: nipype/interfaces/diffusion_toolkit/odf.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,12 @@ class HARDIMat(CommandLine):
9898

9999
def _create_gradient_matrix(self, bvecs_file, bvals_file):
100100
_gradient_matrix_file = "gradient_matrix.txt"
101-
bvals = [val for val in re.split(r"\s+", open(bvals_file).readline().strip())]
102-
bvecs_f = open(bvecs_file)
103-
bvecs_x = [val for val in re.split(r"\s+", bvecs_f.readline().strip())]
104-
bvecs_y = [val for val in re.split(r"\s+", bvecs_f.readline().strip())]
105-
bvecs_z = [val for val in re.split(r"\s+", bvecs_f.readline().strip())]
106-
bvecs_f.close()
101+
with open(bvals_file) as bvals_f:
102+
bvals = bvals_f.readline().strip().split()
103+
with open(bvecs_file) as bvecs_f:
104+
bvecs_x = bvecs_f.readline().strip().split()
105+
bvecs_y = bvecs_f.readline().strip().split()
106+
bvecs_z = bvecs_f.readline().strip().split()
107107
gradient_matrix_f = open(_gradient_matrix_file, "w")
108108
for i in range(len(bvals)):
109109
if int(bvals[i]) == 0:

Diff for: nipype/interfaces/freesurfer/preprocess.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -692,11 +692,11 @@ def _get_runs(self):
692692
if self.inputs.seq_list:
693693
if self.inputs.ignore_single_slice:
694694
if (int(s[8]) > 1) and any(
695-
[s[12].startswith(sn) for sn in self.inputs.seq_list]
695+
s[12].startswith(sn) for sn in self.inputs.seq_list
696696
):
697697
runs.append(int(s[2]))
698698
else:
699-
if any([s[12].startswith(sn) for sn in self.inputs.seq_list]):
699+
if any(s[12].startswith(sn) for sn in self.inputs.seq_list):
700700
runs.append(int(s[2]))
701701
else:
702702
runs.append(int(s[2]))

Diff for: nipype/interfaces/fsl/model.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1503,8 +1503,8 @@ def _run_interface(self, runtime):
15031503
regs = sorted(self.inputs.regressors.keys())
15041504
nwaves = len(regs)
15051505
npoints = len(self.inputs.regressors[regs[0]])
1506-
ntcons = sum([1 for con in self.inputs.contrasts if con[1] == "T"])
1507-
nfcons = sum([1 for con in self.inputs.contrasts if con[1] == "F"])
1506+
ntcons = sum(1 for con in self.inputs.contrasts if con[1] == "T")
1507+
nfcons = sum(1 for con in self.inputs.contrasts if con[1] == "F")
15081508
# write mat file
15091509
mat_txt = ["/NumWaves %d" % nwaves, "/NumPoints %d" % npoints]
15101510
ppheights = []
@@ -1591,7 +1591,7 @@ def _run_interface(self, runtime):
15911591

15921592
def _list_outputs(self):
15931593
outputs = self._outputs().get()
1594-
nfcons = sum([1 for con in self.inputs.contrasts if con[1] == "F"])
1594+
nfcons = sum(1 for con in self.inputs.contrasts if con[1] == "F")
15951595
for field in list(outputs.keys()):
15961596
if ("fts" in field) and (nfcons == 0):
15971597
continue

Diff for: nipype/interfaces/io.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -942,7 +942,7 @@ def _list_outputs(self):
942942
# get list of all files in s3 bucket
943943
conn = boto.connect_s3(anon=self.inputs.anon)
944944
bkt = conn.get_bucket(self.inputs.bucket)
945-
bkt_files = list(k.key for k in bkt.list(prefix=self.inputs.bucket_path))
945+
bkt_files = [k.key for k in bkt.list(prefix=self.inputs.bucket_path)]
946946

947947
# keys are outfields, args are template args for the outfield
948948
for key, args in list(self.inputs.template_args.items()):
@@ -1022,7 +1022,7 @@ def _list_outputs(self):
10221022
if self.inputs.sort_filelist:
10231023
outfiles = human_order_sorted(outfiles)
10241024
outputs[key].append(simplify_list(outfiles))
1025-
if any([val is None for val in outputs[key]]):
1025+
if None in outputs[key]:
10261026
outputs[key] = []
10271027
if len(outputs[key]) == 0:
10281028
outputs[key] = None
@@ -1297,7 +1297,7 @@ def _list_outputs(self):
12971297
if self.inputs.drop_blank_outputs:
12981298
outputs[key] = [x for x in outputs[key] if x is not None]
12991299
else:
1300-
if any([val is None for val in outputs[key]]):
1300+
if None in outputs[key]:
13011301
outputs[key] = []
13021302
if len(outputs[key]) == 0:
13031303
outputs[key] = None
@@ -2302,7 +2302,7 @@ def __init__(self, input_names, **inputs):
23022302
super().__init__(**inputs)
23032303

23042304
self._input_names = ensure_list(input_names)
2305-
add_traits(self.inputs, [name for name in self._input_names])
2305+
add_traits(self.inputs, self._input_names)
23062306

23072307
def _list_outputs(self):
23082308
"""Execute this module."""
@@ -2364,7 +2364,7 @@ def __init__(self, input_names, **inputs):
23642364
super().__init__(**inputs)
23652365

23662366
self._input_names = ensure_list(input_names)
2367-
add_traits(self.inputs, [name for name in self._input_names])
2367+
add_traits(self.inputs, self._input_names)
23682368

23692369
def _list_outputs(self):
23702370
"""Execute this module."""
@@ -2642,7 +2642,7 @@ def _list_outputs(self):
26422642
outputs[key].append(self._get_files_over_ssh(filledtemplate))
26432643

26442644
# disclude where there was any invalid matches
2645-
if any([val is None for val in outputs[key]]):
2645+
if None in outputs[key]:
26462646
outputs[key] = []
26472647

26482648
# no outputs is None, not empty list

Diff for: nipype/interfaces/spm/model.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def _parse_inputs(self):
159159
"""validate spm realign options if set to None ignore"""
160160
einputs = super()._parse_inputs(skip=("mask_threshold", "flags"))
161161
if isdefined(self.inputs.flags):
162-
einputs[0].update({flag: val for (flag, val) in self.inputs.flags.items()})
162+
einputs[0].update(self.inputs.flags)
163163
for sessinfo in einputs[0]["sess"]:
164164
sessinfo["scans"] = scans_for_fnames(
165165
ensure_list(sessinfo["scans"]), keep4d=False
@@ -309,7 +309,7 @@ def _parse_inputs(self):
309309
"""validate spm realign options if set to None ignore"""
310310
einputs = super()._parse_inputs(skip=("flags"))
311311
if isdefined(self.inputs.flags):
312-
einputs[0].update({flag: val for (flag, val) in self.inputs.flags.items()})
312+
einputs[0].update(self.inputs.flags)
313313
return einputs
314314

315315
def _list_outputs(self):

Diff for: nipype/interfaces/utility/wrappers.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,9 @@ def __init__(
9595
self.inputs.on_trait_change(self._set_function_string, "function_str")
9696
self._input_names = ensure_list(input_names)
9797
self._output_names = ensure_list(output_names)
98-
add_traits(self.inputs, [name for name in self._input_names])
98+
add_traits(self.inputs, self._input_names)
9999
self.imports = imports
100-
self._out = {}
101-
for name in self._output_names:
102-
self._out[name] = None
100+
self._out = {name: None for name in self._output_names}
103101

104102
def _set_function_string(self, obj, name, old, new):
105103
if name == "function_str":

Diff for: nipype/pipeline/engine/nodes.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ def needed_outputs(self):
240240
@needed_outputs.setter
241241
def needed_outputs(self, new_outputs):
242242
"""Needed outputs changes the hash, refresh if changed"""
243-
new_outputs = sorted(list(set(new_outputs or [])))
243+
new_outputs = sorted(set(new_outputs or []))
244244
if new_outputs != self._needed_outputs:
245245
# Reset hash
246246
self._hashvalue = None
@@ -1283,7 +1283,7 @@ def _collate_results(self, nodes):
12831283
)
12841284
setattr(finalresult.outputs, key, values)
12851285

1286-
if returncode and any([code is not None for code in returncode]):
1286+
if returncode and any(code is not None for code in returncode):
12871287
msg = []
12881288
for i, code in enumerate(returncode):
12891289
if code is not None:

Diff for: nipype/pipeline/engine/utils.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -1046,7 +1046,7 @@ def make_field_func(*pair):
10461046
logger.debug("node: %s iterables: %s", inode, iterables)
10471047

10481048
# collect the subnodes to expand
1049-
subnodes = [s for s in dfs_preorder(graph_in, inode)]
1049+
subnodes = list(dfs_preorder(graph_in, inode))
10501050
prior_prefix = [re.findall(r"\.(.)I", s._id) for s in subnodes if s._id]
10511051
prior_prefix = sorted([l for item in prior_prefix for l in item])
10521052
if not prior_prefix:
@@ -1482,11 +1482,8 @@ def clean_working_directory(
14821482
files2remove = []
14831483
if str2bool(config["execution"]["remove_unnecessary_outputs"]):
14841484
for f in walk_files(cwd):
1485-
if f not in needed_files:
1486-
if not needed_dirs:
1487-
files2remove.append(f)
1488-
elif not any([f.startswith(dname) for dname in needed_dirs]):
1489-
files2remove.append(f)
1485+
if f not in needed_files and not f.startswith(tuple(needed_dirs)):
1486+
files2remove.append(f)
14901487
else:
14911488
if not str2bool(config["execution"]["keep_inputs"]):
14921489
input_files = {

Diff for: nipype/pipeline/engine/workflows.py

+4-8
Original file line numberDiff line numberDiff line change
@@ -191,10 +191,8 @@ def connect(self, *args, **kwargs):
191191
and (
192192
".io" in str(destnode._interface.__class__)
193193
or any(
194-
[
195-
".io" in str(val)
196-
for val in destnode._interface.__class__.__bases__
197-
]
194+
".io" in str(val)
195+
for val in destnode._interface.__class__.__bases__
198196
)
199197
)
200198
):
@@ -205,10 +203,8 @@ def connect(self, *args, **kwargs):
205203
and (
206204
".io" in str(srcnode._interface.__class__)
207205
or any(
208-
[
209-
".io" in str(val)
210-
for val in srcnode._interface.__class__.__bases__
211-
]
206+
".io" in str(val)
207+
for val in srcnode._interface.__class__.__bases__
212208
)
213209
)
214210
):

Diff for: nipype/pipeline/plugins/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,7 @@ def _remove_node_deps(self, jobid, crashfile, graph):
455455
dfs_preorder = nx.dfs_preorder
456456
except AttributeError:
457457
dfs_preorder = nx.dfs_preorder_nodes
458-
subnodes = [s for s in dfs_preorder(graph, self.procs[jobid])]
458+
subnodes = list(dfs_preorder(graph, self.procs[jobid]))
459459
for node in subnodes:
460460
idx = self.procs.index(node)
461461
self.proc_done[idx] = True

Diff for: nipype/pipeline/plugins/linear.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def run(self, graph, config, updatehash=False):
5050
# node might fail
5151
crashfile = report_crash(node)
5252
# remove dependencies from queue
53-
subnodes = [s for s in dfs_preorder(graph, node)]
53+
subnodes = list(dfs_preorder(graph, node))
5454
notrun.append(
5555
{"node": node, "dependents": subnodes, "crashfile": crashfile}
5656
)

Diff for: nipype/scripts/instance.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def list_interfaces(module):
3939
the given module.
4040
"""
4141
iface_names = []
42-
for k, v in sorted(list(module.__dict__.items())):
42+
for k, v in sorted(module.__dict__.items()):
4343
if inspect.isclass(v) and issubclass(v, Interface):
4444
iface_names.append(k)
4545
return iface_names

Diff for: nipype/utils/docparse.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ def _parse_doc(doc, style=["--"]):
283283
flag = [
284284
item
285285
for i, item in enumerate(linelist)
286-
if i < 2 and any([item.startswith(s) for s in style]) and len(item) > 1
286+
if i < 2 and item.startswith(tuple(style)) and len(item) > 1
287287
]
288288
if flag:
289289
if len(flag) == 1:

Diff for: nipype/utils/filemanip.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,7 @@ def ensure_list(filename):
499499
elif isinstance(filename, list):
500500
return filename
501501
elif is_container(filename):
502-
return [x for x in filename]
502+
return list(filename)
503503
else:
504504
return None
505505

Diff for: nipype/utils/misc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def trim(docstring, marker=None):
5353
if (
5454
marker is not None
5555
and stripped
56-
and all([s == stripped[0] for s in stripped])
56+
and all(s == stripped[0] for s in stripped)
5757
and stripped[0] not in [":"]
5858
):
5959
line = line.replace(stripped[0], marker)

Diff for: nipype/utils/nipype_cmd.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def listClasses(module=None):
1313
__import__(module)
1414
pkg = sys.modules[module]
1515
print("Available Interfaces:")
16-
for k, v in sorted(list(pkg.__dict__.items())):
16+
for k, v in sorted(pkg.__dict__.items()):
1717
if inspect.isclass(v) and issubclass(v, Interface):
1818
print("\t%s" % k)
1919

0 commit comments

Comments
 (0)