Skip to content

Commit

Permalink
Use f-strings for formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
berland committed Dec 19, 2024
1 parent a95d0d2 commit a509da2
Show file tree
Hide file tree
Showing 27 changed files with 55 additions and 83 deletions.
2 changes: 0 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,6 @@ ignore = [
"PLW1641", # eq-without-hash
"PLR0904", # too-many-public-methods
"PLR1702", # too-many-nested-blocks
"UP032", # f-string
"UP031", # printf-string-formatting
]

# Allow EN DASH (U+2013)
Expand Down
2 changes: 1 addition & 1 deletion src/everest/bin/config_branch_script.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def _updated_initial_guess(conf_controls, opt_controls):
if opt_control_val is None:
print(
"No generated optimization control value found for"
" control {} index {}".format(variable[CK.NAME], var_index)
f" control {variable[CK.NAME]} index {var_index}"
)
return None
else:
Expand Down
4 changes: 2 additions & 2 deletions src/everest/bin/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ def _build_args_parser():
usage=(
"everest <command> [<args>]\n\n"
"The most commonly used everest commands are:\n"
"{commands}\n\n"
f"{EverestMain.methods_help()}\n\n"
"Run everest <command> --help for more information on a command"
).format(commands=EverestMain.methods_help()),
),
)
arg_parser.add_argument("command", help="Subcommand to run")
arg_parser.add_argument(
Expand Down
4 changes: 2 additions & 2 deletions src/everest/config_file_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def _get_definitions(configuration, configpath):
for key, val in ERT_CONFIG_TEMPLATES.items():
if key in defs:
logging.warning(
"Internal key {k} specified by user as {u}. "
"Overriding as {v}".format(k=key, u=defs[key], v=val)
f"Internal key {key} specified by user as {defs[key]}. "
f"Overriding as {val}"
)
defs[key] = f"<{val}>" # ert uses <GEO_ID> as format
else:
Expand Down
7 changes: 2 additions & 5 deletions src/everest/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,7 @@ def export_metadata(config: ExportConfig | None, optimization_output_dir: str):
)
else:
print(
"Batch {} has no available optimization data".format(
md_row[MetaDataColumnNames.BATCH]
)
f"Batch {md_row[MetaDataColumnNames.BATCH]} has no available optimization data"
)
metadata.append(md_row)

Expand Down Expand Up @@ -190,9 +188,8 @@ def check_for_errors(
available_batches_ = available_batches(optimization_output_path)
for batch in set(config.batches).difference(available_batches_):
export_errors.append(
"Batch {} not found in optimization "
f"Batch {batch} not found in optimization "
"results. Skipping for current export."
"".format(batch)
)
config.batches = list(set(config.batches).intersection(available_batches_))

Expand Down
2 changes: 1 addition & 1 deletion src/everest/simulator/everest_to_ert.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ def _is_dir_all_geo(source, ever_config: EverestConfig):
if not os.path.exists(geo_source):
msg = (
"Expected source to exist for data installation, "
"did not find: {}".format(geo_source)
f"did not find: {geo_source}"
)
raise ValueError(msg)

Expand Down
4 changes: 1 addition & 3 deletions src/everest/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ def get_azure_logging_handler():


def version_info():
return ("everest:'{}'\nropt:'{}'\nert:'{}'").format(
ert_version, ropt_version, ert_version
)
return f"everest:'{ert_version}'\nropt:'{ropt_version}'\nert:'{ert_version}'"


def date2str(date):
Expand Down
2 changes: 1 addition & 1 deletion test-data/everest/math_func/jobs/adv_distance3.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def main(argv):

if options.out:
with open(options.out, "w", encoding="utf-8") as f:
f.write("%g \n" % value)
f.write(f"{value:g} \n")
else:
print(value)

Expand Down
4 changes: 2 additions & 2 deletions test-data/everest/math_func/jobs/adv_dump_controls.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ def main(argv):
for name, indices in controls.items():
for idx, val in indices.items():
out_file = "{}{}{}".format(
opts.out_prefix, "{}-{}".format(name, idx), opts.out_suffix
opts.out_prefix, f"{name}-{idx}", opts.out_suffix
)
with open(out_file, "w", encoding="utf-8") as f:
f.write("%g \n" % val)
f.write(f"{val:g} \n")


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion test-data/everest/math_func/jobs/discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def main(argv):

if options.out:
with open(options.out, "w", encoding="utf-8") as f:
f.write("%g \n" % value)
f.write(f"{value:g} \n")
else:
print(value)

Expand Down
2 changes: 1 addition & 1 deletion test-data/everest/math_func/jobs/distance3.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def main(argv):

if options.out:
with open(options.out, "w", encoding="utf-8") as f:
f.write("%g \n" % value)
f.write(f"{value:g} \n")
else:
print(value)

Expand Down
4 changes: 2 additions & 2 deletions test-data/everest/math_func/jobs/dump_controls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ def main(argv):
controls = json.load(f)

for k, v in controls.items():
out_file = "{}{}{}".format(opts.out_prefix, k, opts.out_suffix)
out_file = f"{opts.out_prefix}{k}{opts.out_suffix}"
with open(out_file, "w", encoding="utf-8") as f:
f.write("%g \n" % v)
f.write(f"{v:g} \n")


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion test-data/everest/math_func/jobs/fail_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def main(argv):
options, _ = arg_parser.parse_known_args(args=argv)

if options.fail in os.getcwd():
raise Exception("Failing %s by request!" % options.fail)
raise Exception(f"Failing {options.fail} by request!")

time.sleep(1)

Expand Down
25 changes: 4 additions & 21 deletions tests/everest/entry_points/test_everexport.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,7 @@ def test_everexport_entry_no_usr_def_ecl_keys(mocked_func, cached_example):

# Add export section to config file and set run_export flag to false
with open(config_file, "a", encoding="utf-8") as f:
f.write(
"{export}:\n {keywords}:".format(
export=CK.EXPORT,
keywords=CK.KEYWORDS,
)
)
f.write(f"{CK.EXPORT}:\n {CK.KEYWORDS}:")

everexport_entry([config_file])

Expand Down Expand Up @@ -209,11 +204,7 @@ def test_everexport_entry_internalized_usr_def_ecl_keys(mocked_func, cached_exam

# Add export section to config file and set run_export flag to false
with open(config_file, "a", encoding="utf-8") as f:
f.write(
"{export}:\n {keywords}: {keys}".format(
export=CK.EXPORT, keywords=CK.KEYWORDS, keys=user_def_keys
)
)
f.write(f"{CK.EXPORT}:\n {CK.KEYWORDS}: {user_def_keys}")

everexport_entry([config_file])

Expand Down Expand Up @@ -250,11 +241,7 @@ def test_everexport_entry_non_int_usr_def_ecl_keys(mocked_func, caplog, cached_e

# Add export section to config file and set run_export flag to false
with open(config_file, "a", encoding="utf-8") as f:
f.write(
"{export}:\n {keywords}: {keys}".format(
export=CK.EXPORT, keywords=CK.KEYWORDS, keys=user_def_keys
)
)
f.write(f"{CK.EXPORT}:\n {CK.KEYWORDS}: {user_def_keys}")

with caplog.at_level(logging.DEBUG):
everexport_entry([config_file])
Expand Down Expand Up @@ -297,11 +284,7 @@ def test_everexport_entry_not_available_batches(mocked_func, caplog, cached_exam

# Add export section to config file and set run_export flag to false
with open(config_file, "a", encoding="utf-8") as f:
f.write(
"{export}:\n {batch_key}: {batches}".format(
export=CK.EXPORT, batch_key=CK.BATCHES, batches=user_def_batches
)
)
f.write(f"{CK.EXPORT}:\n {CK.BATCHES}: {user_def_batches}")

with caplog.at_level(logging.DEBUG):
everexport_entry([config_file])
Expand Down
2 changes: 1 addition & 1 deletion tests/everest/test_config_file_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def test_dependent_definitions(copy_mocked_test_data_to_tmp):
string.ascii_lowercase[:-1], string.ascii_lowercase[1:], strict=False
)
for c, cdef in [*list(conseq_chars), (string.ascii_lowercase[-1], "configpath")]:
raw_config[CK.DEFINITIONS][c] = "r{{{{ {} }}}}".format(cdef)
raw_config[CK.DEFINITIONS][c] = f"r{{{{ {cdef} }}}}"

with open(config_file, "w", encoding="utf-8") as f:
yaml = YAML(typ="safe", pure=True)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def main(control_group_name):
control_group = json.load(f)

with open(control_group_name + "_sum", "w", encoding="utf-8") as f_out:
f_out.write("%f" % sum(control_group.values()))
f_out.write(f"{sum(control_group.values()):f}")


if __name__ == "__main__":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def main(argv):

diff = compute_fpr_diff(sum_mock)
with open(target_file, "w", encoding="utf-8") as out:
out.write("{} \n".format(diff))
out.write(f"{diff} \n")


if __name__ == "__main__":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ def compute_npv(sum):
with open("debug.txt", "w", encoding="utf-8") as f:
DCF = compute_dcf(fopt[0], fwpt[0], fgpt[0], fwit[0], elapsedtime[0])
f.write(
"%f\t%f\t%f\t%f\t%f\t%f\n"
% (elapsedtime[0], fopt[0], fwpt[0], fgpt[0], fwit[0], DCF)
f"{elapsedtime[0]:f}\t{fopt[0]:f}\t{fwpt[0]:f}\t{fgpt[0]:f}\t{fwit[0]:f}\t{DCF:f}\n"
)
NPV = DCF

Expand All @@ -51,8 +50,7 @@ def compute_npv(sum):
)
NPV += DCF
f.write(
"%f\t%f\t%f\t%f\t%f\t%f\n"
% (elapsedtime[i], fopt[i], fwpt[i], fgpt[i], fwit[i], DCF)
f"{elapsedtime[i]:f}\t{fopt[i]:f}\t{fwpt[i]:f}\t{fgpt[i]:f}\t{fwit[i]:f}\t{DCF:f}\n"
)

return NPV
Expand All @@ -78,7 +76,7 @@ def compute_dcf(voilp, vwaterp, vgasp, vwateri, elapsedtime):

def save_object_value(object_value, target_file):
with open(target_file, "w", encoding="utf-8") as f:
f.write("%g \n" % object_value)
f.write(f"{object_value:g} \n")


def main(argv):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def main(argv):

for i in range(0, len(times)):
val = sum.get("FOPR")[i]
save_return_value(val, "oil_prod_rate_%03d" % i)
save_return_value(val, f"oil_prod_rate_{i:03d}")

with open("OIL_PROD_RATE_OK", "w", encoding="utf-8") as f:
f.write("Everything went fine here!")
Expand Down
4 changes: 2 additions & 2 deletions tests/everest/test_detached.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,13 @@ def test_server_status(copy_math_func_test_data_to_tmp):
)
status = everserver_status(everserver_status_path)
assert status["status"] == ServerStatus.failed
assert status["message"] == "{}\n{}".format(err_msg_1, err_msg_2)
assert status["message"] == f"{err_msg_1}\n{err_msg_2}"

update_everserver_status(everserver_status_path, ServerStatus.completed)
status = everserver_status(everserver_status_path)
assert status["status"] == ServerStatus.completed
assert status["message"] is not None
assert status["message"] == "{}\n{}".format(err_msg_1, err_msg_2)
assert status["message"] == f"{err_msg_1}\n{err_msg_2}"


@patch("everest.detached.server_is_running", return_value=False)
Expand Down
4 changes: 2 additions & 2 deletions tests/everest/test_egg_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,7 +490,7 @@ def _generate_exp_ert_config(config_path, output_dir):
),
(
"symlink",
"{config_path}/../input/files".format(config_path=config_path),
f"{config_path}/../input/files",
"files",
),
(
Expand Down Expand Up @@ -710,7 +710,7 @@ def sweetcallbackofmine(self, *args, **kwargs):
cgname = config.controls[0].name
well_names = [well.name for well in config.wells]
for wname in well_names:
assert "{cg}_{w}-1".format(cg=cgname, w=wname) in df
assert f"{cgname}_{wname}-1" in df

# Check objective export
objective_names = [objf.name for objf in config.objective_functions]
Expand Down
8 changes: 3 additions & 5 deletions tests/everest/test_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,9 +311,7 @@ def check_error(expected_error, reported_errors):

check_error(
(
"Non-internalized ecl keys selected for export '{keys}'." "".format(
keys=non_int_key
),
f"Non-internalized ecl keys selected for export '{non_int_key}'.",
False,
),
(errors, export_ecl),
Expand All @@ -331,8 +329,8 @@ def check_error(expected_error, reported_errors):
)
check_error(
(
"Batch {} not found in optimization results. Skipping for"
" current export".format(non_valid_batch),
f"Batch {non_valid_batch} not found in optimization results. Skipping for"
" current export",
True,
),
(errors, export_ecl),
Expand Down
14 changes: 7 additions & 7 deletions tests/everest/test_math_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,9 @@ def test_math_func_advanced(

ok_evals_0 = ok_evals[ok_evals["realization"] == 0]
best_0 = ok_evals_0.iloc[-1]
assert best_0["point_{}".format(point_names[0])] == pytest.approx(x0)
assert best_0["point_{}".format(point_names[1])] == pytest.approx(x1)
assert best_0["point_{}".format(point_names[2])] == pytest.approx(x2)
assert best_0[f"point_{point_names[0]}"] == pytest.approx(x0)
assert best_0[f"point_{point_names[1]}"] == pytest.approx(x1)
assert best_0[f"point_{point_names[2]}"] == pytest.approx(x2)
assert best_0["distance"] == pytest.approx(-dist_0, abs=0.001)
assert best_0["real_avg_obj"] == pytest.approx(
run_model.result.total_objective, abs=0.001
Expand All @@ -153,9 +153,9 @@ def test_math_func_advanced(

ok_evals_1 = ok_evals[ok_evals["realization"] == 2]
best_1 = ok_evals_1.iloc[-1]
assert best_1["point_{}".format(point_names[0])] == pytest.approx(x0)
assert best_1["point_{}".format(point_names[1])] == pytest.approx(x1)
assert best_1["point_{}".format(point_names[2])] == pytest.approx(x2)
assert best_1[f"point_{point_names[0]}"] == pytest.approx(x0)
assert best_1[f"point_{point_names[1]}"] == pytest.approx(x1)
assert best_1[f"point_{point_names[2]}"] == pytest.approx(x2)
assert best_1["distance"] == pytest.approx(-dist_1, abs=0.001)
assert best_1["real_avg_obj"] == pytest.approx(
run_model.result.total_objective, abs=0.001
Expand Down Expand Up @@ -191,7 +191,7 @@ def test_remove_run_path(
simulation_should_fail = "simulation_2"
# Add to the config dictionary what simulation needs to fail
config.forward_model[config.forward_model.index("toggle_failure")] = (
"toggle_failure --fail %s" % simulation_should_fail
f"toggle_failure --fail {simulation_should_fail}"
)

simulation_dir = config.simulation_dir
Expand Down
2 changes: 1 addition & 1 deletion tests/everest/test_res_initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ def test_summary_default_no_opm(copy_egg_test_data_to_tmp):
list(everest.simulator.DEFAULT_DATA_SUMMARY_KEYS)
+ list(everest.simulator.DEFAULT_FIELD_SUMMARY_KEYS)
+ [
"{}:{}".format(k, w)
f"{k}:{w}"
for k, w in itertools.product(
everest.simulator.DEFAULT_WELL_SUMMARY_KEYS, wells
)
Expand Down
Loading

0 comments on commit a509da2

Please sign in to comment.