Skip to content

Commit 869e69e

Browse files
committed
Replace remaining format calls
1 parent e88d1ba commit 869e69e

20 files changed

+223
-274
lines changed

beets/dbcore/db.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -392,9 +392,9 @@ def _awaken(
392392
return obj
393393

394394
def __repr__(self) -> str:
395-
return "{}({})".format(
396-
type(self).__name__,
397-
", ".join(f"{k}={v!r}" for k, v in dict(self).items()),
395+
return (
396+
f"{type(self).__name__}"
397+
f"({', '.join(f'{k}={v!r}' for k, v in dict(self).items())})"
398398
)
399399

400400
def clear_dirty(self):
@@ -597,9 +597,7 @@ def store(self, fields: Iterable[str] | None = None):
597597
with db.transaction() as tx:
598598
# Main table update.
599599
if assignments:
600-
query = "UPDATE {} SET {} WHERE id=?".format(
601-
self._table, ",".join(assignments)
602-
)
600+
query = f"UPDATE {self._table} SET {','.join(assignments)} WHERE id=?"
603601
subvars.append(self.id)
604602
tx.mutate(query, subvars)
605603

@@ -1174,9 +1172,7 @@ def _make_table(self, table: str, fields: Mapping[str, types.Type]):
11741172
columns = []
11751173
for name, typ in fields.items():
11761174
columns.append(f"{name} {typ.sql}")
1177-
setup_sql = "CREATE TABLE {} ({});\n".format(
1178-
table, ", ".join(columns)
1179-
)
1175+
setup_sql = f"CREATE TABLE {table} ({', '.join(columns)});\n"
11801176

11811177
else:
11821178
# Table exists does not match the field set.
@@ -1196,8 +1192,7 @@ def _make_attribute_table(self, flex_table: str):
11961192
for the given entity (if they don't exist).
11971193
"""
11981194
with self.transaction() as tx:
1199-
tx.script(
1200-
f"""
1195+
tx.script(f"""
12011196
CREATE TABLE IF NOT EXISTS {flex_table} (
12021197
id INTEGER PRIMARY KEY,
12031198
entity_id INTEGER,
@@ -1206,8 +1201,7 @@ def _make_attribute_table(self, flex_table: str):
12061201
UNIQUE(entity_id, key) ON CONFLICT REPLACE);
12071202
CREATE INDEX IF NOT EXISTS {flex_table}_by_entity
12081203
ON {flex_table} (entity_id);
1209-
"""
1210-
)
1204+
""")
12111205

12121206
# Querying.
12131207

beets/library/models.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -844,9 +844,9 @@ def __repr__(self):
844844
# This must not use `with_album=True`, because that might access
845845
# the database. When debugging, that is not guaranteed to succeed, and
846846
# can even deadlock due to the database lock.
847-
return "{}({})".format(
848-
type(self).__name__,
849-
", ".join(f"{k}={self[k]!r}" for k in self.keys(with_album=False)),
847+
return (
848+
f"{type(self).__name__}"
849+
f"({', '.join(f'{k}={self[k]!r}' for k in self.keys(with_album=False))})"
850850
)
851851

852852
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
@@ -517,8 +517,8 @@ def feat_tokens(for_artist: bool = True) -> str:
517517
feat_words = ["ft", "featuring", "feat", "feat.", "ft."]
518518
if for_artist:
519519
feat_words += ["with", "vs", "and", "con", "&"]
520-
return r"(?<=[\s(\[])(?:{})(?=\s)".format(
521-
"|".join(re.escape(x) for x in feat_words)
520+
return (
521+
rf"(?<=[\s(\[])(?:{'|'.join(re.escape(x) for x in feat_words)})(?=\s)"
522522
)
523523

524524

beets/ui/__init__.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1150,7 +1150,7 @@ def show_model_changes(new, old=None, fields=None, always=False):
11501150
continue
11511151

11521152
changes.append(
1153-
" {}: {}".format(field, colorize("text_highlight", new_fmt[field]))
1153+
f" {field}: {colorize('text_highlight', new_fmt[field])}"
11541154
)
11551155

11561156
# Print changes.
@@ -1196,17 +1196,11 @@ def show_path_changes(path_changes):
11961196
# Print every change on a single line, and add a header
11971197
title_pad = max_width - len("Source ") + len(" -> ")
11981198

1199-
print_("Source {0} Destination".format(" " * title_pad))
1199+
print_(f"Source {' ' * title_pad} Destination")
12001200
for source, dest in zip(sources, destinations):
12011201
pad = max_width - len(source)
12021202
color_source, color_dest = colordiff(source, dest)
1203-
print_(
1204-
"{0} {1} -> {2}".format(
1205-
color_source,
1206-
" " * pad,
1207-
color_dest,
1208-
)
1209-
)
1203+
print_(f"{color_source} {' ' * pad} -> {color_dest}")
12101204

12111205

12121206
# Helper functions for option parsing.
@@ -1665,8 +1659,8 @@ def _ensure_db_directory_exists(path):
16651659
newpath = os.path.dirname(path)
16661660
if not os.path.isdir(newpath):
16671661
if input_yn(
1668-
f"The database directory {util.displayable_path(newpath)} does not \
1669-
exist. Create it (Y/n)?"
1662+
f"The database directory {util.displayable_path(newpath)} does not"
1663+
" exist. Create it (Y/n)?"
16701664
):
16711665
os.makedirs(newpath)
16721666

@@ -1686,7 +1680,8 @@ def _open_library(config):
16861680
except (sqlite3.OperationalError, sqlite3.DatabaseError) as db_error:
16871681
log.debug("{}", traceback.format_exc())
16881682
raise UserError(
1689-
f"database file {util.displayable_path(dbpath)} cannot not be opened: {db_error}"
1683+
f"database file {util.displayable_path(dbpath)} cannot not be"
1684+
f" opened: {db_error}"
16901685
)
16911686
log.debug(
16921687
"library database: {0}\nlibrary directory: {1}",

beets/ui/commands.py

Lines changed: 42 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,13 @@ def _parse_logfiles(logfiles):
112112
yield from _paths_from_logfile(syspath(normpath(logfile)))
113113
except ValueError as err:
114114
raise ui.UserError(
115-
f"malformed logfile {util.displayable_path(logfile)}: {str(err)}"
115+
f"malformed logfile {util.displayable_path(logfile)}:"
116+
f" {str(err)}"
116117
) from err
117118
except OSError as err:
118119
raise ui.UserError(
119-
f"unreadable logfile {util.displayable_path(logfile)}: {str(err)}"
120+
f"unreadable logfile {util.displayable_path(logfile)}:"
121+
f" {str(err)}"
120122
) from err
121123

122124

@@ -291,7 +293,7 @@ def penalty_string(distance, limit=None):
291293
if limit and len(penalties) > limit:
292294
penalties = penalties[:limit] + ["..."]
293295
# Prefix penalty string with U+2260: Not Equal To
294-
penalty_string = "\u2260 {}".format(", ".join(penalties))
296+
penalty_string = f"\u2260 {', '.join(penalties)}"
295297
return ui.colorize("changed", penalty_string)
296298

297299

@@ -693,7 +695,9 @@ def show_match_tracks(self):
693695
# Missing and unmatched tracks.
694696
if self.match.extra_tracks:
695697
print_(
696-
f"Missing tracks ({len(self.match.extra_tracks)}/{len(self.match.info.tracks)} - {len(self.match.extra_tracks) / len(self.match.info.tracks):.1%}):"
698+
"Missing tracks"
699+
f" ({len(self.match.extra_tracks)}/{len(self.match.info.tracks)} -"
700+
f" {len(self.match.extra_tracks) / len(self.match.info.tracks):.1%}):"
697701
)
698702
for track_info in self.match.extra_tracks:
699703
line = f" ! {track_info.title} (#{self.format_index(track_info)})"
@@ -783,7 +787,10 @@ def summarize_items(items, singleton):
783787
total_filesize = sum([item.filesize for item in items])
784788
summary_parts.append(f"{int(average_bitrate / 1000)}kbps")
785789
if items[0].format == "FLAC":
786-
sample_bits = f"{round(int(items[0].samplerate) / 1000, 1)}kHz/{items[0].bitdepth} bit"
790+
sample_bits = (
791+
f"{round(int(items[0].samplerate) / 1000, 1)}kHz"
792+
f"/{items[0].bitdepth} bit"
793+
)
787794
summary_parts.append(sample_bits)
788795
summary_parts.append(human_seconds_short(total_duration))
789796
summary_parts.append(human_bytes(total_filesize))
@@ -900,11 +907,9 @@ def choose_candidate(
900907
# Display list of candidates.
901908
print_("")
902909
print_(
903-
'Finding tags for {} "{} - {}".'.format(
904-
"track" if singleton else "album",
905-
item.artist if singleton else cur_artist,
906-
item.title if singleton else cur_album,
907-
)
910+
f"Finding tags for {'track' if singleton else 'album'}"
911+
f'"{item.artist if singleton else cur_artist} -'
912+
f' {item.title if singleton else cur_album}".'
908913
)
909914

910915
print_(ui.indent(2) + "Candidates:")
@@ -914,7 +919,10 @@ def choose_candidate(
914919
index = dist_colorize(index0, match.distance)
915920
dist = f"({(1 - match.distance) * 100:.1f}%)"
916921
distance = dist_colorize(dist, match.distance)
917-
metadata = f"{match.info.artist} - {match.info.title if singleton else match.info.album}"
922+
metadata = (
923+
f"{match.info.artist} -"
924+
f" {match.info.title if singleton else match.info.album}"
925+
)
918926
if i == 0:
919927
metadata = dist_colorize(metadata, match.distance)
920928
else:
@@ -1002,7 +1010,7 @@ def manual_id(session, task):
10021010
10031011
Input an ID, either for an album ("release") or a track ("recording").
10041012
"""
1005-
prompt = "Enter {} ID:".format("release" if task.is_album else "recording")
1013+
prompt = f"Enter {'release' if task.is_album else 'recording'} ID:"
10061014
search_id = input_(prompt).strip()
10071015

10081016
if task.is_album:
@@ -1304,7 +1312,8 @@ def import_files(lib, paths: list[bytes], query):
13041312
loghandler = logging.FileHandler(logpath, encoding="utf-8")
13051313
except OSError:
13061314
raise ui.UserError(
1307-
f"Could not open log file for writing: {displayable_path(logpath)}"
1315+
"Could not open log file for writing:"
1316+
f" {displayable_path(logpath)}"
13081317
)
13091318
else:
13101319
loghandler = None
@@ -1791,22 +1800,25 @@ def remove_items(lib, query, album, delete, force):
17911800
if not force:
17921801
# Prepare confirmation with user.
17931802
album_str = (
1794-
" in {} album{}".format(len(albums), "s" if len(albums) > 1 else "")
1803+
f" in {len(albums)} album{'s' if len(albums) > 1 else ''}"
17951804
if album
17961805
else ""
17971806
)
17981807

17991808
if delete:
18001809
fmt = "$path - $title"
18011810
prompt = "Really DELETE"
1802-
prompt_all = "Really DELETE {} file{}{}".format(
1803-
len(items), "s" if len(items) > 1 else "", album_str
1811+
prompt_all = (
1812+
"Really DELETE"
1813+
f" {len(items)} file{'s' if len(items) > 1 else ''}{album_str}"
18041814
)
18051815
else:
18061816
fmt = ""
18071817
prompt = "Really remove from the library?"
1808-
prompt_all = "Really remove {} item{}{} from the library?".format(
1809-
len(items), "s" if len(items) > 1 else "", album_str
1818+
prompt_all = (
1819+
"Really remove"
1820+
f" {len(items)} item{'s' if len(items) > 1 else ''}{album_str}"
1821+
" from the library?"
18101822
)
18111823

18121824
# Helpers for printing affected items
@@ -1889,23 +1901,13 @@ def show_stats(lib, query, exact):
18891901
if exact:
18901902
size_str += f" ({total_size} bytes)"
18911903

1892-
print_(
1893-
"""Tracks: {}
1894-
Total time: {}{}
1895-
{}: {}
1896-
Artists: {}
1897-
Albums: {}
1898-
Album artists: {}""".format(
1899-
total_items,
1900-
human_seconds(total_time),
1901-
f" ({total_time:.2f} seconds)" if exact else "",
1902-
"Total size" if exact else "Approximate total size",
1903-
size_str,
1904-
len(artists),
1905-
len(albums),
1906-
len(album_artists),
1907-
),
1908-
)
1904+
print_(f"""Tracks: {total_items}
1905+
Total time: {human_seconds(total_time)}
1906+
{f" ({total_time:.2f} seconds)" if exact else ""}
1907+
{"Total size" if exact else "Approximate total size"}: {size_str}
1908+
Artists: {len(artists)}
1909+
Albums: {len(albums)}
1910+
Album artists: {len(album_artists)}""")
19091911

19101912

19111913
def stats_func(lib, opts, args):
@@ -1960,7 +1962,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm, inherit):
19601962

19611963
# Apply changes *temporarily*, preview them, and collect modified
19621964
# objects.
1963-
print_("Modifying {} {}s.".format(len(objs), "album" if album else "item"))
1965+
print_(f"Modifying {len(objs)} {'album' if album else 'item'}s.")
19641966
changed = []
19651967
templates = {
19661968
key: functemplate.template(value) for key, value in mods.items()
@@ -2467,7 +2469,7 @@ def completion_script(commands):
24672469
# Command aliases
24682470
yield " local aliases='%s'\n" % " ".join(aliases.keys())
24692471
for alias, cmd in aliases.items():
2470-
yield " local alias__{}={}\n".format(alias.replace("-", "_"), cmd)
2472+
yield f" local alias__{alias.replace('-', '_')}={cmd}\n"
24712473
yield "\n"
24722474

24732475
# Fields
@@ -2483,8 +2485,9 @@ def completion_script(commands):
24832485
for option_type, option_list in opts.items():
24842486
if option_list:
24852487
option_list = " ".join(option_list)
2486-
yield " local {}__{}='{}'\n".format(
2487-
option_type, cmd.replace("-", "_"), option_list
2488+
yield (
2489+
" local"
2490+
f" {option_type}__{cmd.replace('-', '_')}='{option_list}'\n"
24882491
)
24892492

24902493
yield " _beet_dispatch\n"

beets/util/__init__.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,12 +141,16 @@ def __init__(self, reason, verb, paths, tb=None):
141141
def get_message(self):
142142
# Use a nicer English phrasing for some specific verbs.
143143
if self.verb in ("move", "copy", "rename"):
144-
clause = f"while {self._gerund()} {displayable_path(self.paths[0])} to {displayable_path(self.paths[1])}"
144+
clause = (
145+
f"while {self._gerund()} {displayable_path(self.paths[0])} to"
146+
f" {displayable_path(self.paths[1])}"
147+
)
145148
elif self.verb in ("delete", "write", "create", "read"):
146149
clause = f"while {self._gerund()} {displayable_path(self.paths[0])}"
147150
else:
148-
clause = "during {} of paths {}".format(
149-
self.verb, ", ".join(displayable_path(p) for p in self.paths)
151+
clause = (
152+
f"during {self.verb} of paths"
153+
f" {', '.join(displayable_path(p) for p in self.paths)}"
150154
)
151155

152156
return f"{self._reasonstr()} {clause}"
@@ -219,7 +223,8 @@ def sorted_walk(
219223
except OSError as exc:
220224
if logger:
221225
logger.warning(
222-
f"could not list directory {displayable_path(bytes_path)}: {exc.strerror}"
226+
f"could not list directory {displayable_path(bytes_path)}:"
227+
f" {exc.strerror}"
223228
)
224229
return
225230
dirs = []

beetsplug/aura.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -780,20 +780,17 @@ def audio_file(track_id):
780780
return AURADocument.error(
781781
"404 Not Found",
782782
"No audio file for the requested track.",
783-
(
784-
f"There is no audio file for track {track_id} at the expected location"
785-
),
783+
f"There is no audio file for track {track_id} at the expected"
784+
" location",
786785
)
787786

788787
file_mimetype = guess_type(path)[0]
789788
if not file_mimetype:
790789
return AURADocument.error(
791790
"500 Internal Server Error",
792791
"Requested audio file has an unknown mimetype.",
793-
(
794-
"The audio file for track {} has an unknown mimetype. "
795-
"Its file extension is {}."
796-
).format(track_id, path.split(".")[-1]),
792+
f"The audio file for track {track_id} has an unknown mimetype. "
793+
f"Its file extension is {path.split('.')[-1]}.",
797794
)
798795

799796
# Check that the Accept header contains the file's mimetype
@@ -805,10 +802,8 @@ def audio_file(track_id):
805802
return AURADocument.error(
806803
"406 Not Acceptable",
807804
"Unsupported MIME type or bitrate parameter in Accept header.",
808-
(
809-
f"The audio file for track {track_id} is only available as {file_mimetype} and "
810-
"bitrate parameters are not supported."
811-
),
805+
f"The audio file for track {track_id} is only available as"
806+
f" {file_mimetype} and bitrate parameters are not supported.",
812807
)
813808

814809
return send_file(

0 commit comments

Comments
 (0)