Skip to content

Commit ed8f56e

Browse files
kroenleinclaude
andcommitted
Convert str.format calls to f-strings
Rewrite every str.format call site in gemd and tests as an f-string. The rendered strings are unchanged, since both forms dispatch to __format__. Ruff's UP032 rule generated 44 of these. It skipped two call sites, which this commit rewrites by hand: each nested a double-quoted string inside its format arguments, and an f-string expression cannot reuse the enclosing quote character before Python 3.12. Both now use single quotes inside the expression, which Python 3.9 accepts. Leave UP032 out of the ruff rule selection. This is a one-time improvement rather than a standing rule. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 6512072 commit ed8f56e

26 files changed

Lines changed: 48 additions & 74 deletions

‎gemd/demo/cake.py‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -279,17 +279,15 @@ def _make_ingredient(*, material, process, **kwargs):
279279
tags=list(material.tags),
280280
material=material,
281281
process=process,
282-
uids={
283-
DEMO_SCOPE: "{}--{}".format(material.uids[DEMO_SCOPE], process.uids[DEMO_SCOPE])
284-
},
282+
uids={DEMO_SCOPE: f"{material.uids[DEMO_SCOPE]}--{process.uids[DEMO_SCOPE]}"},
285283
**kwargs,
286284
)
287285

288286
def _make_material(
289287
*, material_name, template, process_tmpl_name, process_kwargs, **material_kwargs
290288
):
291289
"""Convenience method to reuse material name in creating a material's arguments."""
292-
process_name = "{} {}".format(process_tmpl_name, material_name)
290+
process_name = f"{process_tmpl_name} {material_name}"
293291
return MaterialSpec(
294292
name=material_name,
295293
uids={DEMO_SCOPE: material_name.lower().replace(" ", "-")},
@@ -725,22 +723,22 @@ def _randomize_object(item: BaseEntity):
725723
if not isinstance(item, (MaterialRun, ProcessRun, IngredientRun)):
726724
return
727725

728-
item.add_uid(DEMO_SCOPE, "{}-{}".format(item.spec.uids[DEMO_SCOPE], run_key))
726+
item.add_uid(DEMO_SCOPE, f"{item.spec.uids[DEMO_SCOPE]}-{run_key}")
729727
if item.spec.tags is not None:
730728
item.tags = list(item.spec.tags)
731729
if item.spec.notes: # Neither None nor empty string
732-
item.notes = 'The spec says "{}"'.format(item.spec.notes)
730+
item.notes = f'The spec says "{item.spec.notes}"'
733731
if isinstance(item, MaterialRun):
734732
if "raw material" in item.tags:
735733
if "produce" in item.tags:
736734
supplier = random.choice(producers)
737735
else:
738736
supplier = random.choice(drygoods)
739-
item.name = "{} {}".format(supplier, item.spec.name)
737+
item.name = f"{supplier} {item.spec.name}"
740738
if isinstance(item, ProcessRun):
741739
if item.template.name == "Procuring":
742740
item.source = PerformedSource(performed_by="hamilton", performed_date="2015-02-17")
743-
item.name = "{} {}".format(item.template.name, item.output_material.name)
741+
item.name = f"{item.template.name} {item.output_material.name}"
744742
else:
745743
item.source = cake_obj.process.source
746744
if isinstance(item, IngredientRun):
@@ -831,9 +829,7 @@ def _find_name(name, material):
831829
msr.spec.add_uid(DEMO_SCOPE, msr.spec.name.lower())
832830
msr.add_uid(
833831
DEMO_SCOPE,
834-
"{}--{}-{}".format(
835-
msr.spec.uids[DEMO_SCOPE], msr.material.spec.uids[DEMO_SCOPE], run_key
836-
),
832+
f"{msr.spec.uids[DEMO_SCOPE]}--{msr.material.spec.uids[DEMO_SCOPE]}-{run_key}",
837833
)
838834

839835
######################################################################

‎gemd/demo/material_run_example.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def _parse_value(val):
5252
try:
5353
unit = units.parse_units(toks[-1])
5454
except (ValueError, units.UndefinedUnitError):
55-
print("Couldn't find {}".format(toks[-1]))
55+
print(f"Couldn't find {toks[-1]}")
5656
unit = ""
5757

5858
if std >= 0:
@@ -70,7 +70,7 @@ def _parse_value(val):
7070
except ValueError:
7171
return DiscreteCategorical(val)
7272
else:
73-
raise ValueError("Couldn't parse {}".format(val))
73+
raise ValueError(f"Couldn't parse {val}")
7474

7575

7676
def ingest_material_run(data, material_spec=None, process_run=None):
@@ -79,7 +79,7 @@ def ingest_material_run(data, material_spec=None, process_run=None):
7979
return [ingest_material_run(x, material_spec) for x in data]
8080

8181
if not isinstance(data, dict):
82-
raise ValueError("This ingester operates on dict, but got {}".format(type(data)))
82+
raise ValueError(f"This ingester operates on dict, but got {type(data)}")
8383

8484
material = MaterialRun("Material Run")
8585

‎gemd/demo/strehlow_and_cook.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,7 @@ def make_display_table(structured):
472472
"""
473473
table = [[]]
474474
header_map = {
475-
RealBounds: lambda bnd: "Mean({})".format(bnd.default_units),
475+
RealBounds: lambda bnd: f"Mean({bnd.default_units})",
476476
CategoricalBounds: lambda bnd: "Category",
477477
CompositionBounds: lambda bnd: "Formula",
478478
type(None): lambda bnd: "Label",
@@ -487,7 +487,7 @@ def make_display_table(structured):
487487
column = structured["headers"][i_bandgap]
488488
table[0].insert(
489489
i_bandgap + 1,
490-
"~".join(column["name"] + ["Std Deviation({})".format(column["bounds"].default_units)]),
490+
"~".join(column["name"] + [f"Std Deviation({column['bounds'].default_units})"]),
491491
)
492492

493493
content_map = {
@@ -540,7 +540,7 @@ def make_display_table(structured):
540540
full_table = make_strehlow_table(full_compounds)
541541
small_table = minimal_subset(full_table["content"])
542542
todo = set(_fingerprint(x) for x in small_table)
543-
print("Total number of prototypes: {}".format(len(small_table)))
543+
print(f"Total number of prototypes: {len(small_table)}")
544544

545545
reduced_list = []
546546
for raw, clean in zip(imported_table, full_table["content"]):

‎gemd/entity/attribute/base_attribute.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,7 @@ def template(self, template: Optional[Union[AttributeTemplate, LinkByUID]]):
9999
self._check(template, self.value)
100100
self._template = template
101101
else:
102-
raise TypeError(
103-
"template must be a BaseAttributeTemplate or LinkByUID: {}".format(template)
104-
)
102+
raise TypeError(f"template must be a BaseAttributeTemplate or LinkByUID: {template}")
105103

106104
@staticmethod
107105
@abstractmethod

‎gemd/entity/bounds/base_bounds.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def contains(self, bounds: Union[BaseBoundsType, BaseValueType]):
3838
bounds = bounds._to_bounds()
3939
if isinstance(bounds, BaseBounds):
4040
return True
41-
raise TypeError("{} is not a Bounds object".format(bounds))
41+
raise TypeError(f"{bounds} is not a Bounds object")
4242

4343
@abstractmethod
4444
def union(self, *others: Union[BaseBoundsType, BaseValueType]) -> BaseBoundsType:

‎gemd/entity/bounds/composition_bounds.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def components(self, value: Iterable[str]):
4040
elif isinstance(value, set):
4141
self._components = value
4242
else:
43-
raise ValueError("Components must be a list, tuple, or set: {}".format(value))
43+
raise ValueError(f"Components must be a list, tuple, or set: {value}")
4444

4545
if not all(isinstance(x, str) for x in self.components):
4646
raise ValueError("All the components must be strings")

‎gemd/entity/case_insensitive_dict.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -161,9 +161,7 @@ def update(self, mapping: Optional[Mapping[str, Any]] = None, **kwargs) -> None:
161161
prev = self.lowercase_dict[key.lower()]
162162
if prev != key:
163163
raise ValueError(
164-
"Key '{}' already exists in dict with different case: '{}'".format(
165-
key, prev
166-
)
164+
f"Key '{key}' already exists in dict with different case: '{prev}'"
167165
)
168166
if no_mapping:
169167
super().update(**kwargs)
@@ -185,7 +183,5 @@ def _register_key(self, key: str) -> None:
185183
"""
186184
prev = self.lowercase_dict.get(key.lower())
187185
if prev is not None and prev != key:
188-
raise ValueError(
189-
"Key '{}' already exists in dict with different case: '{}'".format(key, prev)
190-
)
186+
raise ValueError(f"Key '{key}' already exists in dict with different case: '{prev}'")
191187
self.lowercase_dict[key.lower()] = key

‎gemd/entity/dict_serializable.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,7 @@ def from_dict(cls, d: Mapping[str, Any]) -> DictSerializableType:
8282
if name in expected_arg_names:
8383
kwargs[name] = arg
8484
elif name != "type":
85-
logger.warning(
86-
"Ignoring unexpected keyword argument in {}: {}".format(cls.__name__, name)
87-
)
85+
logger.warning(f"Ignoring unexpected keyword argument in {cls.__name__}: {name}")
8886
# noinspection PyArgumentList
8987
# DictSerializable's constructor is not intended for use,
9088
# but all of its children will use from_dict like this.

‎gemd/entity/object/ingredient_run.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def material(self, material: Union[MaterialRun, LinkByUID]):
122122
self._material = material
123123
else:
124124
raise TypeError(
125-
"IngredientRun.material must be a MaterialRun or LinkByUID: {}".format(material)
125+
f"IngredientRun.material must be a MaterialRun or LinkByUID: {material}"
126126
)
127127

128128
@property
@@ -141,9 +141,7 @@ def process(self, process: Union[ProcessRun, LinkByUID]):
141141
if isinstance(process, ProcessRun):
142142
process.ingredients.append(self)
143143
else:
144-
raise TypeError(
145-
"IngredientRun.process must be a ProcessRun or LinkByUID: {}".format(process)
146-
)
144+
raise TypeError(f"IngredientRun.process must be a ProcessRun or LinkByUID: {process}")
147145

148146
@staticmethod
149147
def _spec_type() -> Type:

‎gemd/entity/object/ingredient_spec.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def process(self, process: Union[ProcessSpec, LinkByUID]):
133133
process.ingredients.append(self)
134134
else:
135135
raise TypeError(
136-
"IngredientSpec.process must be a ProcessSpec or LinkByUID: {}".format(process)
136+
f"IngredientSpec.process must be a ProcessSpec or LinkByUID: {process}"
137137
)
138138

139139
@property

0 commit comments

Comments
 (0)