Skip to content

Commit a05f9fc

Browse files
committed
Use f-strings instead of string concat
1 parent c01dd6f commit a05f9fc

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+254
-277
lines changed

beets/art.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ def extract(log, outpath, item):
192192
if not ext:
193193
log.warning("Unknown image type in {0}.", displayable_path(item.path))
194194
return
195-
outpath += bytestring_path("." + ext)
195+
outpath += bytestring_path(f".{ext}")
196196

197197
log.info(
198198
"Extracting album art from: {0} to: {1}",

beets/dbcore/db.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -590,7 +590,7 @@ def store(self, fields: Iterable[str] | None = None):
590590
for key in fields:
591591
if key != "id" and key in self._dirty:
592592
self._dirty.remove(key)
593-
assignments.append(key + "=?")
593+
assignments.append(f"{key}=?")
594594
value = self._type(key).to_sql(self[key])
595595
subvars.append(value)
596596

beets/dbcore/query.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ class MatchQuery(FieldQuery[AnySQLiteType]):
190190
"""A query that looks for exact matches in an Model field."""
191191

192192
def col_clause(self) -> tuple[str, Sequence[SQLiteType]]:
193-
return self.field + " = ?", [self.pattern]
193+
return f"{self.field} = ?", [self.pattern]
194194

195195
@classmethod
196196
def value_match(cls, pattern: AnySQLiteType, value: Any) -> bool:
@@ -204,7 +204,7 @@ def __init__(self, field, fast: bool = True):
204204
super().__init__(field, None, fast)
205205

206206
def col_clause(self) -> tuple[str, Sequence[SQLiteType]]:
207-
return self.field + " IS NULL", ()
207+
return f"{self.field} IS NULL", ()
208208

209209
def match(self, obj: Model) -> bool:
210210
return obj.get(self.field_name) is None
@@ -246,7 +246,7 @@ def col_clause(self) -> tuple[str, Sequence[SQLiteType]]:
246246
.replace("%", "\\%")
247247
.replace("_", "\\_")
248248
)
249-
clause = self.field + " like ? escape '\\'"
249+
clause = f"{self.field} like ? escape '\\'"
250250
subvals = [search]
251251
return clause, subvals
252252

@@ -264,8 +264,8 @@ def col_clause(self) -> tuple[str, Sequence[SQLiteType]]:
264264
.replace("%", "\\%")
265265
.replace("_", "\\_")
266266
)
267-
search = "%" + pattern + "%"
268-
clause = self.field + " like ? escape '\\'"
267+
search = f"%{pattern}%"
268+
clause = f"{self.field} like ? escape '\\'"
269269
subvals = [search]
270270
return clause, subvals
271271

@@ -471,7 +471,7 @@ def match(self, obj: Model) -> bool:
471471

472472
def col_clause(self) -> tuple[str, Sequence[SQLiteType]]:
473473
if self.point is not None:
474-
return self.field + "=?", (self.point,)
474+
return f"{self.field}=?", (self.point,)
475475
else:
476476
if self.rangemin is not None and self.rangemax is not None:
477477
return (
@@ -549,9 +549,9 @@ def clause_with_joiner(
549549
if not subq_clause:
550550
# Fall back to slow query.
551551
return None, ()
552-
clause_parts.append("(" + subq_clause + ")")
552+
clause_parts.append(f"({subq_clause})")
553553
subvals += subq_subvals
554-
clause = (" " + joiner + " ").join(clause_parts)
554+
clause = f" {joiner} ".join(clause_parts)
555555
return clause, subvals
556556

557557
def __repr__(self) -> str:

beets/library/exceptions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,11 @@ class ReadError(FileOperationError):
2828
"""An error while reading a file (i.e. in `Item.read`)."""
2929

3030
def __str__(self):
31-
return "error reading " + str(super())
31+
return f"error reading {super()}"
3232

3333

3434
class WriteError(FileOperationError):
3535
"""An error while writing a file (i.e. in `Item.write`)."""
3636

3737
def __str__(self):
38-
return "error writing " + str(super())
38+
return f"error writing {super()}"

beets/plugins.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ def load_plugins(names: Sequence[str] = ()) -> None:
291291
namespace = __import__(modname, None, None)
292292
except ImportError as exc:
293293
# Again, this is hacky:
294-
if exc.args[0].endswith(" " + name):
294+
if exc.args[0].endswith(f" {name}"):
295295
log.warning("** plugin {0} not found", name)
296296
else:
297297
raise

beets/test/_common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def __init__(self, out=None):
153153
self.out = out
154154

155155
def add(self, s):
156-
self.buf.append(s + "\n")
156+
self.buf.append(f"{s}\n")
157157

158158
def close(self):
159159
pass

beets/test/helper.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ def create_item(self, **values):
278278
values_["db"] = self.lib
279279
item = Item(**values_)
280280
if "path" not in values:
281-
item["path"] = "audio." + item["format"].lower()
281+
item["path"] = f"audio.{item['format'].lower()}"
282282
# mtime needs to be set last since other assignments reset it.
283283
item.mtime = 12345
284284
return item
@@ -310,7 +310,7 @@ def add_item_fixture(self, **values):
310310
item = self.create_item(**values)
311311
extension = item["format"].lower()
312312
item["path"] = os.path.join(
313-
_common.RSRC, util.bytestring_path("min." + extension)
313+
_common.RSRC, util.bytestring_path(f"min.{extension}")
314314
)
315315
item.add(self.lib)
316316
item.move(operation=MoveOperation.COPY)
@@ -325,7 +325,7 @@ def add_item_fixtures(self, ext="mp3", count=1):
325325
"""Add a number of items with files to the database."""
326326
# TODO base this on `add_item()`
327327
items = []
328-
path = os.path.join(_common.RSRC, util.bytestring_path("full." + ext))
328+
path = os.path.join(_common.RSRC, util.bytestring_path(f"full.{ext}"))
329329
for i in range(count):
330330
item = Item.from_path(path)
331331
item.album = f"\u00e4lbum {i}" # Check unicode paths
@@ -372,7 +372,7 @@ def create_mediafile_fixture(self, ext="mp3", images=[]):
372372
specified extension a cover art image is added to the media
373373
file.
374374
"""
375-
src = os.path.join(_common.RSRC, util.bytestring_path("full." + ext))
375+
src = os.path.join(_common.RSRC, util.bytestring_path(f"full.{ext}"))
376376
handle, path = mkstemp(dir=self.temp_dir)
377377
path = bytestring_path(path)
378378
os.close(handle)
@@ -568,7 +568,7 @@ def prepare_track_for_import(
568568
medium = MediaFile(track_path)
569569
medium.update(
570570
{
571-
"album": "Tag Album" + (f" {album_id}" if album_id else ""),
571+
"album": f"Tag Album{f' {album_id}' if album_id else ''}",
572572
"albumartist": None,
573573
"mb_albumid": None,
574574
"comp": None,
@@ -854,8 +854,8 @@ def _make_album_match(self, artist, album, tracks, distance=0, missing=0):
854854
album=album,
855855
tracks=track_infos,
856856
va=False,
857-
album_id="albumid" + id,
858-
artist_id="artistid" + id,
857+
album_id=f"albumid{id}",
858+
artist_id=f"artistid{id}",
859859
albumtype="soundtrack",
860860
data_source="match_source",
861861
bandcamp_album_id="bc_url",
@@ -881,7 +881,7 @@ def run(self, *args, **kwargs):
881881
super().run(*args, **kwargs)
882882

883883
IMAGEHEADER: dict[str, bytes] = {
884-
"image/jpeg": b"\xff\xd8\xff" + b"\x00" * 3 + b"JFIF",
884+
"image/jpeg": b"\xff\xd8\xff\x00\x00\x00JFIF",
885885
"image/png": b"\211PNG\r\n\032\n",
886886
"image/gif": b"GIF89a",
887887
# dummy type that is definitely not a valid image content type

beets/ui/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ def input_options(
325325

326326
if line_length != 0:
327327
# Not the beginning of the line; need a space.
328-
part = " " + part
328+
part = f" {part}"
329329
length += 1
330330

331331
prompt += part
@@ -337,7 +337,7 @@ def input_options(
337337
fallback_prompt = "Enter one of "
338338
if numrange:
339339
fallback_prompt += "{}-{}, ".format(*numrange)
340-
fallback_prompt += ", ".join(display_letters) + ":"
340+
fallback_prompt += f"{', '.join(display_letters)}:"
341341

342342
resp = input_(prompt)
343343
while True:
@@ -481,7 +481,7 @@ def input_select_objects(prompt, objs, rep, prompt_all=None):
481481
"bg_cyan": 46,
482482
"bg_white": 47,
483483
}
484-
RESET_COLOR = COLOR_ESCAPE + "39;49;00m"
484+
RESET_COLOR = f"{COLOR_ESCAPE}39;49;00m"
485485

486486
# These abstract COLOR_NAMES are lazily mapped on to the actual color in COLORS
487487
# as they are defined in the configuration files, see function: colorize
@@ -521,7 +521,7 @@ def _colorize(color, text):
521521
# over all "ANSI codes" in `color`.
522522
escape = ""
523523
for code in color:
524-
escape = escape + COLOR_ESCAPE + f"{ANSI_CODES[code]}m"
524+
escape = f"{escape}{COLOR_ESCAPE}{ANSI_CODES[code]}m"
525525
return escape + text + RESET_COLOR
526526

527527

@@ -1492,7 +1492,7 @@ def format_help(self, formatter=None):
14921492

14931493
# Concatenate the original help message with the subcommand
14941494
# list.
1495-
return out + "".join(result)
1495+
return f"{out}{''.join(result)}"
14961496

14971497
def _subcommand_for_name(self, name):
14981498
"""Return the subcommand in self.subcommands matching the

beets/ui/commands.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import os
2020
import re
21+
import textwrap
2122
from collections import Counter
2223
from collections.abc import Sequence
2324
from itertools import chain
@@ -136,7 +137,7 @@ def _print_keys(query):
136137
def fields_func(lib, opts, args):
137138
def _print_rows(names):
138139
names.sort()
139-
print_(f" {'\n '.join(names)}")
140+
print_(textwrap.indent("\n".join(names), " "))
140141

141142
print_("Item fields:")
142143
_print_rows(library.Item.all_keys())
@@ -358,18 +359,18 @@ def show_match_header(self):
358359

359360
# 'Match' line and similarity.
360361
print_(
361-
self.indent_header + f"Match ({dist_string(self.match.distance)}):"
362+
f"{self.indent_header}Match ({dist_string(self.match.distance)}):"
362363
)
363364

364365
if isinstance(self.match.info, autotag.hooks.AlbumInfo):
365366
# Matching an album - print that
366367
artist_album_str = (
367-
f"{self.match.info.artist}" + f" - {self.match.info.album}"
368+
f"{self.match.info.artist} - {self.match.info.album}"
368369
)
369370
else:
370371
# Matching a single track
371372
artist_album_str = (
372-
f"{self.match.info.artist}" + f" - {self.match.info.title}"
373+
f"{self.match.info.artist} - {self.match.info.title}"
373374
)
374375
print_(
375376
self.indent_header
@@ -395,6 +396,7 @@ def show_match_details(self):
395396
"""Print out the details of the match, including changes in album name
396397
and artist name.
397398
"""
399+
changed_prefix = ui.colorize("changed", "\u2260")
398400
# Artist.
399401
artist_l, artist_r = self.cur_artist or "", self.match.info.artist
400402
if artist_r == VARIOUS_ARTISTS:
@@ -404,15 +406,15 @@ def show_match_details(self):
404406
artist_l, artist_r = ui.colordiff(artist_l, artist_r)
405407
# Prefix with U+2260: Not Equal To
406408
left = {
407-
"prefix": ui.colorize("changed", "\u2260") + " Artist: ",
409+
"prefix": f"{changed_prefix} Artist: ",
408410
"contents": artist_l,
409411
"suffix": "",
410412
}
411413
right = {"prefix": "", "contents": artist_r, "suffix": ""}
412414
self.print_layout(self.indent_detail, left, right)
413415

414416
else:
415-
print_(self.indent_detail + "*", "Artist:", artist_r)
417+
print_(f"{self.indent_detail}*", "Artist:", artist_r)
416418

417419
if self.cur_album:
418420
# Album
@@ -424,29 +426,29 @@ def show_match_details(self):
424426
album_l, album_r = ui.colordiff(album_l, album_r)
425427
# Prefix with U+2260: Not Equal To
426428
left = {
427-
"prefix": ui.colorize("changed", "\u2260") + " Album: ",
429+
"prefix": f"{changed_prefix} Album: ",
428430
"contents": album_l,
429431
"suffix": "",
430432
}
431433
right = {"prefix": "", "contents": album_r, "suffix": ""}
432434
self.print_layout(self.indent_detail, left, right)
433435
else:
434-
print_(self.indent_detail + "*", "Album:", album_r)
436+
print_(f"{self.indent_detail}*", "Album:", album_r)
435437
elif self.cur_title:
436438
# Title - for singletons
437439
title_l, title_r = self.cur_title or "", self.match.info.title
438440
if self.cur_title != self.match.info.title:
439441
title_l, title_r = ui.colordiff(title_l, title_r)
440442
# Prefix with U+2260: Not Equal To
441443
left = {
442-
"prefix": ui.colorize("changed", "\u2260") + " Title: ",
444+
"prefix": f"{changed_prefix} Title: ",
443445
"contents": title_l,
444446
"suffix": "",
445447
}
446448
right = {"prefix": "", "contents": title_r, "suffix": ""}
447449
self.print_layout(self.indent_detail, left, right)
448450
else:
449-
print_(self.indent_detail + "*", "Title:", title_r)
451+
print_(f"{self.indent_detail}*", "Title:", title_r)
450452

451453
def make_medium_info_line(self, track_info):
452454
"""Construct a line with the current medium's info."""
@@ -570,9 +572,9 @@ def make_line(self, item, track_info):
570572

571573
prefix = ui.colorize("changed", "\u2260 ") if changed else "* "
572574
lhs = {
573-
"prefix": prefix + lhs_track + " ",
575+
"prefix": f"{prefix}{lhs_track} ",
574576
"contents": lhs_title,
575-
"suffix": " " + lhs_length,
577+
"suffix": f" {lhs_length}",
576578
}
577579
rhs = {"prefix": "", "contents": "", "suffix": ""}
578580
if not changed:
@@ -581,9 +583,9 @@ def make_line(self, item, track_info):
581583
else:
582584
# Construct a dictionary for the "changed to" side
583585
rhs = {
584-
"prefix": rhs_track + " ",
586+
"prefix": f"{rhs_track} ",
585587
"contents": rhs_title,
586-
"suffix": " " + rhs_length,
588+
"suffix": f" {rhs_length}",
587589
}
588590
return (lhs, rhs)
589591

@@ -909,7 +911,7 @@ def choose_candidate(
909911
f' {item.title if singleton else cur_album}".'
910912
)
911913

912-
print_(ui.indent(2) + "Candidates:")
914+
print_(" Candidates:")
913915
for i, match in enumerate(candidates):
914916
# Index, metadata, and distance.
915917
index0 = f"{i + 1}."
@@ -925,17 +927,17 @@ def choose_candidate(
925927
else:
926928
metadata = ui.colorize("text_highlight_minor", metadata)
927929
line1 = [index, distance, metadata]
928-
print_(ui.indent(2) + " ".join(line1))
930+
print_(f" {' '.join(line1)}")
929931

930932
# Penalties.
931933
penalties = penalty_string(match.distance, 3)
932934
if penalties:
933-
print_(ui.indent(13) + penalties)
935+
print_(f"{' ' * 13}{penalties}")
934936

935937
# Disambiguation
936938
disambig = disambig_string(match.info)
937939
if disambig:
938-
print_(ui.indent(13) + disambig)
940+
print_(f"{' ' * 13}{disambig}")
939941

940942
# Ask the user for a choice.
941943
sel = ui.input_options(choice_opts, numrange=(1, len(candidates)))
@@ -1894,7 +1896,7 @@ def show_stats(lib, query, exact):
18941896
if item.album_id:
18951897
albums.add(item.album_id)
18961898

1897-
size_str = "" + human_bytes(total_size)
1899+
size_str = human_bytes(total_size)
18981900
if exact:
18991901
size_str += f" ({total_size} bytes)"
19001902

0 commit comments

Comments
 (0)