Skip to content

Commit

Permalink
Use f-strings for formatting strings (#88).
Browse files Browse the repository at this point in the history
  • Loading branch information
jendrikseipp committed Aug 3, 2020
1 parent 9c501e4 commit 3b3007d
Show file tree
Hide file tree
Showing 28 changed files with 162 additions and 205 deletions.
2 changes: 1 addition & 1 deletion dev/make-release-notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def check(name, text):
print("*" * 60)
print(text)
print("*" * 60)
response = input("Accept this %s (Y/n)? " % name).strip().lower()
response = input(f"Accept this {name} (Y/n)? ").strip().lower()
if response and response != "y":
sys.exit(1)

Expand Down
2 changes: 2 additions & 0 deletions dev/release.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ function set_version {

cd $(dirname "$0")/../

source .venv/bin/activate

# Check for uncommited changes.
set +e
git diff --quiet && git diff --cached --quiet
Expand Down
1 change: 1 addition & 0 deletions docs/news.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Lab
* Separate tests for Singularity and FF example experiments from other tests (Jendrik Seipp).
* Skip ``cached_revision`` doctests if ``DOWNWARD_REVISION_CACHE`` variable is not set (Jendrik Seipp).
* Add ``.github/CONTRIBUTING.md`` file (Jendrik Seipp).
* For developers: use f-strings to format strings (Jendrik Seipp).

Downward Lab
^^^^^^^^^^^^
Expand Down
3 changes: 1 addition & 2 deletions downward/experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,8 +319,7 @@ def add_algorithm(
for algo in self._algorithms.values():
if algorithm == algo:
logging.critical(
"Algorithms {algo.name} and {algorithm.name} are "
"identical.".format(**locals())
f"Algorithms {algo.name} and {algorithm.name} are identical."
)
self._algorithms[name] = algorithm

Expand Down
2 changes: 1 addition & 1 deletion downward/outcomes.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,5 @@ def get_outcome(exitcode, use_legacy_exit_codes):
elif not use_legacy_exit_codes and exitcode in EXITCODE_TO_OUTCOME:
return EXITCODE_TO_OUTCOME[exitcode]
else:
msg = "exitcode-{exitcode}".format(**locals())
msg = f"exitcode-{exitcode}"
return Outcome(exitcode, msg, explained=False, min_wins=True)
31 changes: 13 additions & 18 deletions downward/reports/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,25 +157,20 @@ def _scan_planning_data(self):
)
func = logging.info if num_unexplained_errors == 0 else logging.error
func(
"Report contains {num_unexplained_errors} runs with unexplained"
" errors.".format(**locals())
f"Report contains {num_unexplained_errors} runs with unexplained"
f" errors."
)

if len(problems) * len(self.algorithms) != len(self.runs):
logging.warning(
"Not every algorithm has been run on every task. "
"However, if you applied a filter this is to be "
"expected. If not, there might be old properties in the "
"eval-dir that got included in the report. "
"Algorithms (%d): %s, problems (%d), domains (%d): %s, runs (%d)"
% (
len(self.algorithms),
self.algorithms,
len(problems),
len(self.domains),
list(self.domains.keys()),
len(self.runs),
)
f"Not every algorithm has been run on every task. "
f"However, if you applied a filter this is to be "
f"expected. If not, there might be old properties in the "
f"eval-dir that got included in the report. "
f"Algorithms ({len(self.algorithms)}): {self.algorithms}, "
f"problems ({len(problems)}), "
f"domains ({len(self.domains)}): {list(self.domains.keys())}, "
f"runs ({len(self.runs)})"
)

# Sort each entry in problem_runs by algorithm.
Expand Down Expand Up @@ -267,11 +262,11 @@ def _get_warnings_text_and_table(self):
else:
slurm_err_content = tools.filter_slurm_err_content(slurm_err_content)

logging.error("There was output to {slurm_err_file}.".format(**locals()))
logging.error(f"There was output to {slurm_err_file}.")

errors.append(
' Contents of {slurm_err_file} without "memory cg"'
" errors:\n```\n{slurm_err_content}\n```".format(**locals())
f' Contents of {slurm_err_file} without "memory cg"'
f" errors:\n```\n{slurm_err_content}\n```"
)

if table:
Expand Down
54 changes: 22 additions & 32 deletions downward/reports/absolute.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def flush_buffer():
if match:
infai_node_id = int(match.group(1))
if sequence_buffer:
if sequence_buffer[-1] == "ase{:02d}".format(infai_node_id - 1):
if sequence_buffer[-1] == f"ase{infai_node_id - 1:02d}":
sequence_buffer.append(node)
elif len(sequence_buffer) in [1, 2]:
flush_buffer()
Expand Down Expand Up @@ -116,7 +116,7 @@ def get_markup(self):
toc_lines.append("- **[Summary #summary]**")

for attribute in self.attributes:
logging.info("Creating table(s) for %s" % attribute)
logging.info(f"Creating table(s) for {attribute}")
tables = []
if attribute == "error":
seen_errors = set()
Expand All @@ -142,9 +142,7 @@ def get_markup(self):
if self.use_domain_links:
table.cell_formatters[domain][
table.header_column
] = reports.CellFormatter(
link="#error-{domain}".format(**locals())
)
] = reports.CellFormatter(link=f"#error-{domain}")
for algorithm in self.algorithms:
count = error_counter.get((algorithm, domain, error), 0)
table.add_cell(domain, algorithm, count)
Expand All @@ -163,9 +161,9 @@ def get_markup(self):
tables.append(
(
"",
"Domain-wise reports only support numeric "
"attributes, but %s has type %s."
% (attribute, self._all_attributes[attribute].__name__),
f"Domain-wise reports only support numeric "
f"attributes, but {attribute} has type "
f"{self._all_attributes[attribute].__name__}.",
)
)
for domain in sorted(self.domains.keys()):
Expand All @@ -176,21 +174,16 @@ def get_markup(self):
for (domain, table) in tables:
if domain:
assert table
toc_line.append(
"[''%(domain)s'' #%(attribute)s-%(domain)s]" % locals()
)
parts.append(
"== %(domain)s ==[%(attribute)s-%(domain)s]\n"
"%(table)s\n" % locals()
)
toc_line.append(f"[''{domain}'' #{attribute}-{domain}]")
parts.append(f"== {domain} ==[{attribute}-{domain}]\n{table}\n")
else:
if table:
parts.append("%(table)s\n" % locals())
parts.append(f"{table}\n")
else:
parts.append(
"No task was found where all algorithms "
'have a value for "%s". Therefore no '
"domain-wise table can be generated.\n" % attribute
f"No task was found where all algorithms "
f'have a value for "{attribute}". Therefore no '
f"domain-wise table can be generated.\n"
)

toc_lines.append(f"- **[''{attribute}'' #{attribute}]**")
Expand All @@ -216,9 +209,8 @@ def _get_general_info(self):
table.add_cell(algo, attr, info[attr])
table.set_column_order(self.INFO_ATTRIBUTES)

node_info = "Used nodes: {{{}}}".format(
", ".join(_abbreviate_node_names(self._get_node_names()))
)
used_nodes = ", ".join(_abbreviate_node_names(self._get_node_names()))
node_info = f"Used nodes: {{{used_nodes}}}"

if table:
return str(table) + "\n" + node_info
Expand All @@ -237,24 +229,22 @@ def _add_table_info(self, attribute, func_name, table):
"""
if not attribute.absolute:
table.info.append(
"Only instances where all algorithms have a "
'value for "%s" are considered.' % attribute
f"Only instances where all algorithms have a "
f'value for "{attribute}" are considered.'
)
table.info.append(
'Each table entry gives the %s of "%s" for that '
"domain." % (func_name, attribute)
f'Each table entry gives the {func_name} of "{attribute}" for that '
f"domain."
)

summary_names = [name.lower() for name, _ in table.summary_funcs.items()]
if len(summary_names) == 1:
table.info.append(
"The last row reports the %s across all domains." % summary_names[0]
f"The bottom row reports the {summary_names[0]} across all domains."
)
elif len(summary_names) > 1:
table.info.append(
"The last rows report the %s across all domains."
% " and ".join(summary_names)
)
names = " and ".join(summary_names)
table.info.append(f"The bottom rows report the {names} across all domains.")

def _get_suite_table(self, attribute):
assert self.attribute_is_numeric(attribute), attribute
Expand Down Expand Up @@ -335,7 +325,7 @@ def _get_empty_table(self, attribute=None, title=None, columns=None):
kwargs = {}
table = reports.Table(title=title, **kwargs)
table.set_column_order(columns)
link = "#%s" % title
link = f"#{title}"
formatter = reports.CellFormatter(link=link)
table.cell_formatters[table.header_row][table.header_column] = formatter
return table
Expand Down
2 changes: 1 addition & 1 deletion downward/reports/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def __init__(self, algorithm_pairs, summary_functions):
col_name = None
while col_name is None or col_name in diff_column_names:
uniq_count += 1
col_name = "diff_column_%s" % uniq_count
col_name = f"diff_column_{uniq_count}"
diff_column_names.add(col_name)
self.header_names.append(((tup[0], tup[1]), diff_name, col_name))
self.summary_functions = summary_functions
Expand Down
2 changes: 1 addition & 1 deletion downward/reports/scatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ def _write_plot(self, runs, filename):
def write(self):
if not len(self.algorithms) == 2:
logging.critical(
"Scatter plots need exactly 2 algorithms: %s" % self.algorithms
f"Scatter plots need exactly 2 algorithms: {self.algorithms}"
)
suffix = "." + self.output_format
if not self.outfile.endswith(suffix):
Expand Down
26 changes: 13 additions & 13 deletions downward/reports/scatter_pgfplots.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,16 @@ def _get_plot(cls, report):
options["xmax"] = report.x_upper
if report.y_upper is not None:
options["ymax"] = report.y_upper
lines.append("\\begin{axis}[%s]" % cls._format_options(options))
lines.append(f"\\begin{{axis}}[{cls._format_options(options)}]")
for category, coords in sorted(report.categories.items()):
plot = {"only marks": True}
lines.append(
"\\addplot+[{}] coordinates {{\n{}\n}};".format(
cls._format_options(plot), " ".join(str(c) for c in coords)
cls._format_options({"only marks": True}),
" ".join(str(c) for c in coords),
)
)
if category:
lines.append("\\addlegendentry{%s}" % category)
lines.append(f"\\addlegendentry{{{category}}}")
elif report.has_multiple_categories():
# None is treated as the default category if using multiple
# categories. Add a corresponding entry to the legend.
Expand All @@ -48,16 +48,16 @@ def _get_plot(cls, report):
# Add black line at y=1.
line_min, line_max = cls._get_supported_range(options["xmode"])
lines.append(
"\\draw[color=black] (axis cs:{line_min},1) -- "
"(axis cs:{line_max},1);".format(**locals())
f"\\draw[color=black] (axis cs:{line_min},1) -- "
f"(axis cs:{line_max},1);"
)
if report.plot_diagonal_line:
# Add black diagonal line.
assert options["xmode"] == options["ymode"]
line_min, line_max = cls._get_supported_range(options["xmode"])
lines.append(
"\\draw[color=black] (axis cs:{line_min},{line_min}) -- "
"(axis cs:{line_max},{line_max});".format(**locals())
f"\\draw[color=black] (axis cs:{line_min},{line_min}) -- "
f"(axis cs:{line_max},{line_max});"
)

lines.append("\\end{axis}")
Expand Down Expand Up @@ -86,7 +86,7 @@ def write(cls, report, filename):
)
tools.makedirs(os.path.dirname(filename))
tools.write_file(filename, "\n".join(lines))
logging.info("Wrote file://%s" % filename)
logging.info(f"Wrote file://{filename}")

@classmethod
def _get_axis_options(cls, report):
Expand All @@ -104,8 +104,8 @@ def _get_axis_options(cls, report):
figsize = report.matplotlib_options.get("figure.figsize")
if figsize:
width, height = figsize
axis["width"] = "%.2fin" % width
axis["height"] = "%.2fin" % height
axis["width"] = f"{width:.2f}in"
axis["height"] = f"{height:.2f}in"

if report.has_multiple_categories():
axis["legend style"] = cls._format_options(
Expand All @@ -124,8 +124,8 @@ def _format_options(cls, options):
opts.append(key)
elif isinstance(value, str):
if " " in value or "=" in value:
value = "{%s}" % value
opts.append("{}={}".format(key, value.replace("_", "-")))
value = f"{{{value}}}"
opts.append(f"{key}={value.replace('_', '-')}")
else:
opts.append(f"{key}={value}")
return ", ".join(opts)
2 changes: 1 addition & 1 deletion downward/scripts/single-search-parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@


def _get_states_pattern(attribute, name):
return (attribute, r"{name} (\d+) state\(s\)\.".format(**locals()), int)
return (attribute, rf"{name} (\d+) state\(s\)\.", int)


PATTERNS = [
Expand Down
6 changes: 3 additions & 3 deletions downward/suites.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __str__(self):
return self.domain

def __repr__(self):
return "<Domain %s>" % self.domain
return f"<Domain {self.domain}>"

def __hash__(self):
return hash(self.domain)
Expand Down Expand Up @@ -113,8 +113,8 @@ def __init__(

def __str__(self):
return (
"<Problem {domain}({domain_file}):{problem}({problem_file}):"
"{properties}>".format(**self.__dict__)
f"<Problem {self.domain}({self.domain_file}):{self.problem}"
f"({self.problem_file}):{self.properties}>"
)


Expand Down
2 changes: 1 addition & 1 deletion examples/showcase-options.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def only_two_algorithms(run):


def eval_dir(num):
return os.path.join(exp.eval_dir, "test%d" % num)
return os.path.join(exp.eval_dir, f"test{num}")


exp.add_fetcher(dest=eval_dir(1), name="fetcher-test1", filter=only_two_algorithms)
Expand Down
4 changes: 2 additions & 2 deletions examples/singularity/singularity-exp.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def get_image(name):
"run-planner",
[
"{run_singularity}",
"{%s}" % planner,
f"{{{planner}}}",
"{domain}",
"{problem}",
"sas_plan",
Expand All @@ -113,7 +113,7 @@ def get_image(name):
run.set_property("algorithm", planner)
run.set_property("id", [planner, task.domain, task.problem])

report = os.path.join(exp.eval_dir, "{}.html".format(exp.name))
report = os.path.join(exp.eval_dir, f"{exp.name}.html")
exp.add_report(BaseReport(attributes=ATTRIBUTES), outfile=report)

exp.run_steps()
2 changes: 1 addition & 1 deletion examples/vertex-cover/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def error(content, props):
parser.add_pattern(
"solver_exit_code", r"solve exit code: (.+)\n", type=int, file="driver.log"
)
parser.add_pattern("cover", r"Cover: set\(\[(.*)\]\)", type=str)
parser.add_pattern("cover", r"Cover: (\{.*\})", type=str)
parser.add_pattern("cover_size", r"Cover size: (\d+)\n", type=int)
parser.add_pattern("solve_time", r"Solve time: (.+)s", type=float)
parser.add_function(solved)
Expand Down
8 changes: 4 additions & 4 deletions examples/vertex-cover/solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def main():
args = parse_args()
random.seed(args.seed)
edges = get_edges(args.input_file)
print("Algorithm: {}".format(args.algorithm))
print(f"Algorithm: {args.algorithm}")
start_time = clock()
if args.algorithm == "2approx":
cover = find_two_approximation(edges)
Expand All @@ -78,9 +78,9 @@ def main():
else:
raise ValueError("Unknown algorithm selected")
solve_time = clock() - start_time
print("Cover: {}".format(cover))
print("Cover size: {}".format(len(cover)))
print("Solve time: {}s".format(solve_time))
print(f"Cover: {cover}")
print(f"Cover size: {len(cover)}")
print(f"Solve time: {solve_time}s")


if __name__ == "__main__":
Expand Down

0 comments on commit 3b3007d

Please sign in to comment.