Skip to content

Commit e88d1ba

Browse files
committed
Replace format calls with f-strings
1 parent 0fec858 commit e88d1ba

40 files changed

+151
-283
lines changed

beets/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def read(self, user=True, defaults=True):
3535
except confuse.NotFoundError:
3636
pass
3737
except confuse.ConfigReadError as err:
38-
stderr.write("configuration `import` failed: {}".format(err.reason))
38+
stderr.write(f"configuration `import` failed: {err.reason}")
3939

4040

4141
config = IncludeLazyConfig("beets", __name__)

beets/autotag/distance.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,9 @@ def string_dist(str1: str | None, str2: str | None) -> float:
7979
# "something, the".
8080
for word in SD_END_WORDS:
8181
if str1.endswith(", %s" % word):
82-
str1 = "{} {}".format(word, str1[: -len(word) - 2])
82+
str1 = f"{word} {str1[: -len(word) - 2]}"
8383
if str2.endswith(", %s" % word):
84-
str2 = "{} {}".format(word, str2[: -len(word) - 2])
84+
str2 = f"{word} {str2[: -len(word) - 2]}"
8585

8686
# Perform a couple of basic normalizing substitutions.
8787
for pat, repl in SD_REPLACE:
@@ -230,7 +230,7 @@ def update(self, dist: Distance):
230230
"""Adds all the distance penalties from `dist`."""
231231
if not isinstance(dist, Distance):
232232
raise ValueError(
233-
"`dist` must be a Distance object, not {}".format(type(dist))
233+
f"`dist` must be a Distance object, not {type(dist)}"
234234
)
235235
for key, penalties in dist._penalties.items():
236236
self._penalties.setdefault(key, []).extend(penalties)

beets/dbcore/db.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -411,9 +411,9 @@ def _check_db(self, need_id: bool = True) -> D:
411411
exception is raised otherwise.
412412
"""
413413
if not self._db:
414-
raise ValueError("{} has no database".format(type(self).__name__))
414+
raise ValueError(f"{type(self).__name__} has no database")
415415
if need_id and not self.id:
416-
raise ValueError("{} has no id".format(type(self).__name__))
416+
raise ValueError(f"{type(self).__name__} has no id")
417417

418418
return self._db
419419

@@ -608,9 +608,9 @@ def store(self, fields: Iterable[str] | None = None):
608608
if key in self._dirty:
609609
self._dirty.remove(key)
610610
tx.mutate(
611-
"INSERT INTO {} "
611+
f"INSERT INTO {self._flex_table} "
612612
"(entity_id, key, value) "
613-
"VALUES (?, ?, ?);".format(self._flex_table),
613+
"VALUES (?, ?, ?);",
614614
(self.id, key, value),
615615
)
616616

@@ -1184,8 +1184,8 @@ def _make_table(self, table: str, fields: Mapping[str, types.Type]):
11841184
for name, typ in fields.items():
11851185
if name in current_fields:
11861186
continue
1187-
setup_sql += "ALTER TABLE {} ADD COLUMN {} {};\n".format(
1188-
table, name, typ.sql
1187+
setup_sql += (
1188+
f"ALTER TABLE {table} ADD COLUMN {name} {typ.sql};\n"
11891189
)
11901190

11911191
with self.transaction() as tx:
@@ -1197,16 +1197,16 @@ def _make_attribute_table(self, flex_table: str):
11971197
"""
11981198
with self.transaction() as tx:
11991199
tx.script(
1200-
"""
1201-
CREATE TABLE IF NOT EXISTS {0} (
1200+
f"""
1201+
CREATE TABLE IF NOT EXISTS {flex_table} (
12021202
id INTEGER PRIMARY KEY,
12031203
entity_id INTEGER,
12041204
key TEXT,
12051205
value TEXT,
12061206
UNIQUE(entity_id, key) ON CONFLICT REPLACE);
1207-
CREATE INDEX IF NOT EXISTS {0}_by_entity
1208-
ON {0} (entity_id);
1209-
""".format(flex_table)
1207+
CREATE INDEX IF NOT EXISTS {flex_table}_by_entity
1208+
ON {flex_table} (entity_id);
1209+
"""
12101210
)
12111211

12121212
# Querying.

beets/dbcore/query.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,7 @@ def col_clause(self) -> tuple[str, Sequence[SQLiteType]]:
475475
else:
476476
if self.rangemin is not None and self.rangemax is not None:
477477
return (
478-
"{0} >= ? AND {0} <= ?".format(self.field),
478+
f"{self.field} >= ? AND {self.field} <= ?",
479479
(self.rangemin, self.rangemax),
480480
)
481481
elif self.rangemin is not None:
@@ -800,9 +800,7 @@ class DateInterval:
800800

801801
def __init__(self, start: datetime | None, end: datetime | None):
802802
if start is not None and end is not None and not start < end:
803-
raise ValueError(
804-
"start date {} is not before end date {}".format(start, end)
805-
)
803+
raise ValueError(f"start date {start} is not before end date {end}")
806804
self.start = start
807805
self.end = end
808806

@@ -1074,9 +1072,9 @@ def order_clause(self) -> str:
10741072
if self.case_insensitive:
10751073
field = (
10761074
"(CASE "
1077-
"WHEN TYPEOF({0})='text' THEN LOWER({0}) "
1078-
"WHEN TYPEOF({0})='blob' THEN LOWER({0}) "
1079-
"ELSE {0} END)".format(self.field)
1075+
f"WHEN TYPEOF({self.field})='text' THEN LOWER({self.field}) "
1076+
f"WHEN TYPEOF({self.field})='blob' THEN LOWER({self.field}) "
1077+
f"ELSE {self.field} END)"
10801078
)
10811079
else:
10821080
field = self.field

beets/dbcore/types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ def __init__(self, unit: int, suffix: str = ""):
219219
self.suffix = suffix
220220

221221
def format(self, value: int) -> str:
222-
return "{}{}".format((value or 0) // self.unit, self.suffix)
222+
return f"{(value or 0) // self.unit}{self.suffix}"
223223

224224

225225
class Id(NullInteger):

beets/importer/stages.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -341,9 +341,7 @@ def _resolve_duplicates(session: ImportSession, task: ImportTask):
341341
if task.choice_flag in (Action.ASIS, Action.APPLY, Action.RETAG):
342342
found_duplicates = task.find_duplicates(session.lib)
343343
if found_duplicates:
344-
log.debug(
345-
"found duplicates: {}".format([o.id for o in found_duplicates])
346-
)
344+
log.debug(f"found duplicates: {[o.id for o in found_duplicates]}")
347345

348346
# Get the default action to follow from config.
349347
duplicate_action = config["import"]["duplicate_action"].as_choice(

beets/library/models.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -846,10 +846,7 @@ def __repr__(self):
846846
# can even deadlock due to the database lock.
847847
return "{}({})".format(
848848
type(self).__name__,
849-
", ".join(
850-
"{}={!r}".format(k, self[k])
851-
for k in self.keys(with_album=False)
852-
),
849+
", ".join(f"{k}={self[k]!r}" for k in self.keys(with_album=False)),
853850
)
854851

855852
def keys(self, computed=False, with_album=True):

beets/plugins.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -370,9 +370,9 @@ def types(model_cls: type[AnyModel]) -> dict[str, Type]:
370370
for field in plugin_types:
371371
if field in types and plugin_types[field] != types[field]:
372372
raise PluginConflictError(
373-
"Plugin {} defines flexible field {} "
373+
f"Plugin {plugin.name} defines flexible field {field} "
374374
"which has already been defined with "
375-
"another type.".format(plugin.name, field)
375+
"another type."
376376
)
377377
types.update(plugin_types)
378378
return types

beets/ui/__init__.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -713,7 +713,7 @@ def get_replacements():
713713
replacements.append((re.compile(pattern), repl))
714714
except re.error:
715715
raise UserError(
716-
"malformed regular expression in replace: {}".format(pattern)
716+
f"malformed regular expression in replace: {pattern}"
717717
)
718718
return replacements
719719

@@ -1191,7 +1191,7 @@ def show_path_changes(path_changes):
11911191
# Print every change over two lines
11921192
for source, dest in zip(sources, destinations):
11931193
color_source, color_dest = colordiff(source, dest)
1194-
print_("{0} \n -> {1}".format(color_source, color_dest))
1194+
print_(f"{color_source} \n -> {color_dest}")
11951195
else:
11961196
# Print every change on a single line, and add a header
11971197
title_pad = max_width - len("Source ") + len(" -> ")
@@ -1232,9 +1232,7 @@ def _store_dict(option, opt_str, value, parser):
12321232
raise ValueError
12331233
except ValueError:
12341234
raise UserError(
1235-
"supplied argument `{}' is not of the form `key=value'".format(
1236-
value
1237-
)
1235+
f"supplied argument `{value}' is not of the form `key=value'"
12381236
)
12391237

12401238
option_values[key] = value
@@ -1413,8 +1411,8 @@ def root_parser(self):
14131411
@root_parser.setter
14141412
def root_parser(self, root_parser):
14151413
self._root_parser = root_parser
1416-
self.parser.prog = "{} {}".format(
1417-
as_string(root_parser.get_prog_name()), self.name
1414+
self.parser.prog = (
1415+
f"{as_string(root_parser.get_prog_name())} {self.name}"
14181416
)
14191417

14201418

@@ -1667,10 +1665,8 @@ def _ensure_db_directory_exists(path):
16671665
newpath = os.path.dirname(path)
16681666
if not os.path.isdir(newpath):
16691667
if input_yn(
1670-
"The database directory {} does not \
1671-
exist. Create it (Y/n)?".format(
1672-
util.displayable_path(newpath)
1673-
)
1668+
f"The database directory {util.displayable_path(newpath)} does not \
1669+
exist. Create it (Y/n)?"
16741670
):
16751671
os.makedirs(newpath)
16761672

@@ -1690,9 +1686,7 @@ def _open_library(config):
16901686
except (sqlite3.OperationalError, sqlite3.DatabaseError) as db_error:
16911687
log.debug("{}", traceback.format_exc())
16921688
raise UserError(
1693-
"database file {} cannot not be opened: {}".format(
1694-
util.displayable_path(dbpath), db_error
1695-
)
1689+
f"database file {util.displayable_path(dbpath)} cannot not be opened: {db_error}"
16961690
)
16971691
log.debug(
16981692
"library database: {0}\nlibrary directory: {1}",

0 commit comments

Comments
 (0)