Skip to content

Commit a40fb2c

Browse files
STY: Apply ruff/pyupgrade rule UP032
UP032 Use f-string instead of `format` call
1 parent c97e210 commit a40fb2c

File tree

16 files changed

+46
-114
lines changed

16 files changed

+46
-114
lines changed

nipype/interfaces/base/tests/test_resource_monitor.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ class UseResources(CommandLine):
5555

5656
@pytest.mark.skip(reason="inconsistent readings")
5757
@pytest.mark.skipif(os.getenv("CI_SKIP_TEST", False), reason="disabled in CI tests")
58-
@pytest.mark.parametrize(("mem_gb", "n_procs"), [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)])
58+
@pytest.mark.parametrize(
59+
("mem_gb", "n_procs"), [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)]
60+
)
5961
def test_cmdline_profiling(tmpdir, mem_gb, n_procs, use_resource_monitor):
6062
"""
6163
Test runtime profiler correctly records workflow RAM/CPUs consumption
@@ -80,7 +82,9 @@ def test_cmdline_profiling(tmpdir, mem_gb, n_procs, use_resource_monitor):
8082
@pytest.mark.skipif(
8183
True, reason="test disabled temporarily, until function profiling works"
8284
)
83-
@pytest.mark.parametrize(("mem_gb", "n_procs"), [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)])
85+
@pytest.mark.parametrize(
86+
("mem_gb", "n_procs"), [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)]
87+
)
8488
def test_function_profiling(tmpdir, mem_gb, n_procs, use_resource_monitor):
8589
"""
8690
Test runtime profiler correctly records workflow RAM/CPUs consumption

nipype/interfaces/spm/utils.py

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -105,22 +105,17 @@ def _make_matlab_command(self, _):
105105
self.inputs.mat = self._make_mat_file()
106106
if not isdefined(self.inputs.invmat):
107107
self.inputs.invmat = self._make_inv_file()
108-
script = """
109-
target = '{}';
110-
moving = '{}';
108+
script = f"""
109+
target = '{self.inputs.target}';
110+
moving = '{self.inputs.moving}';
111111
targetv = spm_vol(target);
112112
movingv = spm_vol(moving);
113113
x = spm_coreg(targetv, movingv);
114114
M = spm_matrix(x);
115-
save('{}' , 'M' );
115+
save('{self.inputs.mat}' , 'M' );
116116
M = inv(M);
117-
save('{}','M')
118-
""".format(
119-
self.inputs.target,
120-
self.inputs.moving,
121-
self.inputs.mat,
122-
self.inputs.invmat,
123-
)
117+
save('{self.inputs.invmat}','M')
118+
"""
124119
return script
125120

126121
def _list_outputs(self):
@@ -166,10 +161,10 @@ def _make_matlab_command(self, _):
166161
"""checks for SPM, generates script"""
167162
outputs = self._list_outputs()
168163
self.inputs.out_file = outputs["out_file"]
169-
script = """
170-
infile = '{}';
171-
outfile = '{}'
172-
transform = load('{}');
164+
script = f"""
165+
infile = '{self.inputs.in_file}';
166+
outfile = '{self.inputs.out_file}'
167+
transform = load('{self.inputs.mat}');
173168
174169
V = spm_vol(infile);
175170
X = spm_read_vols(V);
@@ -178,11 +173,7 @@ def _make_matlab_command(self, _):
178173
V.fname = fullfile(outfile);
179174
spm_write_vol(V,X);
180175
181-
""".format(
182-
self.inputs.in_file,
183-
self.inputs.out_file,
184-
self.inputs.mat,
185-
)
176+
"""
186177
# img_space = spm_get_space(infile);
187178
# spm_get_space(infile, transform.M * img_space);
188179
return script

nipype/interfaces/workbench/metric.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,7 @@ def _format_arg(self, opt, spec, val):
149149
if opt in ["current_area", "new_area"]:
150150
if not self.inputs.area_surfs and not self.inputs.area_metrics:
151151
raise ValueError(
152-
"{} was set but neither area_surfs or"
153-
" area_metrics were set".format(opt)
152+
f"{opt} was set but neither area_surfs or area_metrics were set"
154153
)
155154
if opt == "method":
156155
if (

nipype/pipeline/engine/utils.py

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -369,13 +369,7 @@ def format_node(node, format="python", include_config=False):
369369
args = ", ".join(filled_args)
370370
klass_name = klass.__class__.__name__
371371
if isinstance(node, MapNode):
372-
nodedef = '{} = MapNode({}({}), iterfield={}, name="{}")'.format(
373-
name,
374-
klass_name,
375-
args,
376-
node.iterfield,
377-
name,
378-
)
372+
nodedef = f'{name} = MapNode({klass_name}({args}), iterfield={node.iterfield}, name="{name}")'
379373
else:
380374
nodedef = f'{name} = Node({klass_name}({args}), name="{name}")'
381375
lines = [importline, comment, nodedef]
@@ -782,9 +776,7 @@ def _merge_graphs(
782776
rootnode = list(Gc.nodes())[nodeidx]
783777
paramstr = ""
784778
for key, val in sorted(params.items()):
785-
paramstr = "{}_{}_{}".format(
786-
paramstr, _get_valid_pathstr(key), _get_valid_pathstr(val)
787-
)
779+
paramstr = f"{paramstr}_{_get_valid_pathstr(key)}_{_get_valid_pathstr(val)}"
788780
rootnode.set_input(key, val)
789781

790782
logger.debug("Parameterization: paramstr=%s", paramstr)
@@ -916,10 +908,8 @@ def _propagate_internal_output(graph, node, field, connections, portinputs):
916908
src_func = src_port[1].split("\\n")[0]
917909
dst_func = src[1].split("\\n")[0]
918910
raise ValueError(
919-
"Does not support two inline functions "
920-
"in series ('{}' and '{}'), found when "
921-
"connecting {} to {}. Please use a Function "
922-
"node.".format(src_func, dst_func, srcnode, destnode)
911+
f"Does not support two inline functions in series ('{src_func}' and '{dst_func}'), "
912+
f"found when connecting {srcnode} to {destnode}. Please use a Function node."
923913
)
924914

925915
connect = graph.get_edge_data(srcnode, destnode, default={"connect": []})

nipype/pipeline/engine/workflows.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -444,8 +444,7 @@ def write_graph(
444444
if graph2use in ["hierarchical", "colored"]:
445445
if self.name[:1].isdigit(): # these graphs break if int
446446
raise ValueError(
447-
"{} graph failed, workflow name cannot begin "
448-
"with a number".format(graph2use)
447+
f"{graph2use} graph failed, workflow name cannot begin with a number"
449448
)
450449
dotfilename = op.join(base_dir, dotfilename)
451450
self.write_hierarchical_dotfile(

nipype/pipeline/plugins/base.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -534,11 +534,8 @@ def _get_result(self, taskid):
534534
results_file = None
535535
try:
536536
error_message = (
537-
"Job id ({}) finished or terminated, but "
538-
"results file does not exist after ({}) "
539-
"seconds. Batch dir contains crashdump file "
540-
"if node raised an exception.\n"
541-
"Node working directory: ({}) ".format(taskid, timeout, node_dir)
537+
f"Job id ({taskid}) finished or terminated, but results file does not exist after ({timeout}) seconds. Batch dir contains crashdump file if node raised an exception.\n"
538+
f"Node working directory: ({node_dir}) "
542539
)
543540
raise OSError(error_message)
544541
except OSError:

nipype/pipeline/plugins/lsf.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,7 @@ def _submit_batchtask(self, scriptfile, node):
8585
jobnameitems = jobname.split(".")
8686
jobnameitems.reverse()
8787
jobname = ".".join(jobnameitems)
88-
cmd.inputs.args = "{} -J {} sh {}".format(
89-
bsubargs,
90-
jobname,
91-
scriptfile,
92-
) # -J job_name_spec
88+
cmd.inputs.args = f"{bsubargs} -J {jobname} sh {scriptfile}" # -J job_name_spec
9389
logger.debug("bsub " + cmd.inputs.args)
9490
oldlevel = iflogger.level
9591
iflogger.setLevel(logging.getLevelName("CRITICAL"))

nipype/pipeline/plugins/sge.py

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,7 @@ def is_job_state_pending(self):
8282
time_diff = time.time() - self._job_info_creation_time
8383
if self.is_zombie():
8484
sge_debug_print(
85-
"DONE! QJobInfo.IsPending found in 'zombie' list, returning False so claiming done!\n{}".format(
86-
self
87-
)
85+
f"DONE! QJobInfo.IsPending found in 'zombie' list, returning False so claiming done!\n{self}"
8886
)
8987
is_pending_status = False # Job explicitly found as being completed!
9088
elif self.is_initializing() and (time_diff > 600):
@@ -253,21 +251,15 @@ def _parse_qstat_job_list(self, xml_job_list):
253251
self._task_dictionary[dictionary_job].set_state("zombie")
254252
else:
255253
sge_debug_print(
256-
"ERROR: Job not in current parselist, "
257-
"and not in done list {}: {}".format(
258-
dictionary_job, self._task_dictionary[dictionary_job]
259-
)
254+
f"ERROR: Job not in current parselist, and not in done list {dictionary_job}: {self._task_dictionary[dictionary_job]}"
260255
)
261256
if self._task_dictionary[dictionary_job].is_initializing():
262257
is_completed = self._qacct_verified_complete(dictionary_job)
263258
if is_completed:
264259
self._task_dictionary[dictionary_job].set_state("zombie")
265260
else:
266261
sge_debug_print(
267-
"ERROR: Job not in still in initialization mode, "
268-
"and not in done list {}: {}".format(
269-
dictionary_job, self._task_dictionary[dictionary_job]
270-
)
262+
f"ERROR: Job not in still in initialization mode, and not in done list {dictionary_job}: {self._task_dictionary[dictionary_job]}"
271263
)
272264

273265
def _run_qstat(self, reason_for_qstat, force_instant=True):
@@ -279,8 +271,7 @@ def _run_qstat(self, reason_for_qstat, force_instant=True):
279271
-s s suspended jobs
280272
"""
281273
sge_debug_print(
282-
"WARNING: CONTACTING qmaster for jobs, "
283-
"{}: {}".format(time.time(), reason_for_qstat)
274+
f"WARNING: CONTACTING qmaster for jobs, {time.time()}: {reason_for_qstat}"
284275
)
285276
if force_instant:
286277
this_command = self._qstat_instant_executable
@@ -340,8 +331,7 @@ def is_job_pending(self, task_id):
340331
job_is_pending = self._task_dictionary[task_id].is_job_state_pending()
341332
else:
342333
sge_debug_print(
343-
"ERROR: Job {} not in task list, "
344-
"even after forced qstat!".format(task_id)
334+
f"ERROR: Job {task_id} not in task list, even after forced qstat!"
345335
)
346336
job_is_pending = False
347337
if not job_is_pending:
@@ -352,8 +342,7 @@ def is_job_pending(self, task_id):
352342
self._task_dictionary.pop(task_id)
353343
else:
354344
sge_debug_print(
355-
"ERROR: Job {} not in task list, "
356-
"but attempted to be removed!".format(task_id)
345+
f"ERROR: Job {task_id} not in task list, but attempted to be removed!"
357346
)
358347
return job_is_pending
359348

nipype/pipeline/plugins/sgegraph.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -144,14 +144,7 @@ def make_job_name(jobnumber, nodeslist):
144144
stdoutFile = ""
145145
if self._qsub_args.count("-o ") == 0:
146146
stdoutFile = f"-o {batchscriptoutfile}"
147-
full_line = "{jobNm}=$(qsub {outFileOption} {errFileOption} {extraQSubArgs} {dependantIndex} -N {jobNm} {batchscript} | awk '/^Your job/{{print $3}}')\n".format(
148-
jobNm=jobname,
149-
outFileOption=stdoutFile,
150-
errFileOption=stderrFile,
151-
extraQSubArgs=qsub_args,
152-
dependantIndex=deps,
153-
batchscript=batchscriptfile,
154-
)
147+
full_line = f"{jobname}=$(qsub {stdoutFile} {stderrFile} {qsub_args} {deps} -N {jobname} {batchscriptfile} | awk '/^Your job/{{print $3}}')\n"
155148
fp.writelines(full_line)
156149
cmd = CommandLine(
157150
"bash",

nipype/pipeline/plugins/slurmgraph.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -144,14 +144,7 @@ def make_job_name(jobnumber, nodeslist):
144144
stdoutFile = ""
145145
if self._sbatch_args.count("-o ") == 0:
146146
stdoutFile = f"-o {batchscriptoutfile}"
147-
full_line = "{jobNm}=$(sbatch {outFileOption} {errFileOption} {extraSBatchArgs} {dependantIndex} -J {jobNm} {batchscript} | awk '/^Submitted/ {{print $4}}')\n".format(
148-
jobNm=jobname,
149-
outFileOption=stdoutFile,
150-
errFileOption=stderrFile,
151-
extraSBatchArgs=sbatch_args,
152-
dependantIndex=deps,
153-
batchscript=batchscriptfile,
154-
)
147+
full_line = f"{jobname}=$(sbatch {stdoutFile} {stderrFile} {sbatch_args} {deps} -J {jobname} {batchscriptfile} | awk '/^Submitted/ {{print $4}}')\n"
155148
fp.writelines(full_line)
156149
cmd = CommandLine(
157150
"bash",

0 commit comments

Comments
 (0)