Skip to content

Commit 2d6eeed

Browse files
committed
Replace percent formatting
1 parent 869e69e commit 2d6eeed

24 files changed

+65
-89
lines changed

beets/autotag/distance.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,9 @@ def string_dist(str1: str | None, str2: str | None) -> float:
7878
# example, "the something" should be considered equal to
7979
# "something, the".
8080
for word in SD_END_WORDS:
81-
if str1.endswith(", %s" % word):
81+
if str1.endswith(f", {word}"):
8282
str1 = f"{word} {str1[: -len(word) - 2]}"
83-
if str2.endswith(", %s" % word):
83+
if str2.endswith(f", {word}"):
8484
str2 = f"{word} {str2[: -len(word) - 2]}"
8585

8686
# Perform a couple of basic normalizing substitutions.
@@ -444,7 +444,7 @@ def distance(
444444
# Preferred media options.
445445
media_patterns: Sequence[str] = preferred_config["media"].as_str_seq()
446446
options = [
447-
re.compile(r"(\d+x)?(%s)" % pat, re.I) for pat in media_patterns
447+
re.compile(rf"(\d+x)?({pat})", re.I) for pat in media_patterns
448448
]
449449
if options:
450450
dist.add_priority("media", album_info.media, options)

beets/dbcore/db.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1159,7 +1159,7 @@ def _make_table(self, table: str, fields: Mapping[str, types.Type]):
11591159
"""
11601160
# Get current schema.
11611161
with self.transaction() as tx:
1162-
rows = tx.query("PRAGMA table_info(%s)" % table)
1162+
rows = tx.query(f"PRAGMA table_info({table})")
11631163
current_fields = {row[1] for row in rows}
11641164

11651165
field_names = set(fields.keys())

beets/library/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ def item_dir(self):
482482
"""
483483
item = self.items().get()
484484
if not item:
485-
raise ValueError("empty album for album id %d" % self.id)
485+
raise ValueError(f"empty album for album id {self.id}")
486486
return os.path.dirname(item.path)
487487

488488
def _albumtotal(self):

beets/test/helper.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -829,8 +829,8 @@ def item_candidates(self, item, artist, title):
829829

830830
def _make_track_match(self, artist, album, number):
831831
return TrackInfo(
832-
title="Applied Track %d" % number,
833-
track_id="match %d" % number,
832+
title=f"Applied Track {number}",
833+
track_id=f"match {number}",
834834
artist=artist,
835835
length=1,
836836
index=0,

beets/ui/__init__.py

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ def input_options(
256256
)
257257
):
258258
# The first option is the default; mark it.
259-
show_letter = "[%s]" % found_letter.upper()
259+
show_letter = f"[{found_letter.upper()}]"
260260
is_default = True
261261
else:
262262
show_letter = found_letter.upper()
@@ -295,9 +295,9 @@ def input_options(
295295
if isinstance(default, int):
296296
default_name = str(default)
297297
default_name = colorize("action_default", default_name)
298-
tmpl = "# selection (default %s)"
299-
prompt_parts.append(tmpl % default_name)
300-
prompt_part_lengths.append(len(tmpl % str(default)))
298+
tmpl = "# selection (default {})"
299+
prompt_parts.append(tmpl.format(default_name))
300+
prompt_part_lengths.append(len(tmpl) - 2 + len(str(default)))
301301
else:
302302
prompt_parts.append("# selection")
303303
prompt_part_lengths.append(len(prompt_parts[-1]))
@@ -336,7 +336,7 @@ def input_options(
336336
if not fallback_prompt:
337337
fallback_prompt = "Enter one of "
338338
if numrange:
339-
fallback_prompt += "%i-%i, " % numrange
339+
fallback_prompt += "{}-{}, ".format(*numrange)
340340
fallback_prompt += ", ".join(display_letters) + ":"
341341

342342
resp = input_(prompt)
@@ -393,7 +393,7 @@ def input_select_objects(prompt, objs, rep, prompt_all=None):
393393
objects individually.
394394
"""
395395
choice = input_options(
396-
("y", "n", "s"), False, "%s? (Yes/no/select)" % (prompt_all or prompt)
396+
("y", "n", "s"), False, f"{prompt_all or prompt}? (Yes/no/select)"
397397
)
398398
print() # Blank line.
399399

@@ -407,7 +407,7 @@ def input_select_objects(prompt, objs, rep, prompt_all=None):
407407
answer = input_options(
408408
("y", "n", "q"),
409409
True,
410-
"%s? (yes/no/quit)" % prompt,
410+
f"{prompt}? (yes/no/quit)",
411411
"Enter Y or N:",
412412
)
413413
if answer == "y":
@@ -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 + "%im" % ANSI_CODES[code]
524+
escape = escape + COLOR_ESCAPE + f"{ANSI_CODES[code]}m"
525525
return escape + text + RESET_COLOR
526526

527527

@@ -1462,7 +1462,7 @@ def format_help(self, formatter=None):
14621462
for subcommand in subcommands:
14631463
name = subcommand.name
14641464
if subcommand.aliases:
1465-
name += " (%s)" % ", ".join(subcommand.aliases)
1465+
name += f" ({', '.join(subcommand.aliases)})"
14661466
disp_names.append(name)
14671467

14681468
# Set the help position based on the max width.
@@ -1475,26 +1475,18 @@ def format_help(self, formatter=None):
14751475
# Lifted directly from optparse.py.
14761476
name_width = help_position - formatter.current_indent - 2
14771477
if len(name) > name_width:
1478-
name = "%*s%s\n" % (formatter.current_indent, "", name)
1478+
name = f"{' ' * formatter.current_indent}{name}\n"
14791479
indent_first = help_position
14801480
else:
1481-
name = "%*s%-*s " % (
1482-
formatter.current_indent,
1483-
"",
1484-
name_width,
1485-
name,
1486-
)
1481+
name = f"{' ' * formatter.current_indent}{name:<{name_width}}\n"
14871482
indent_first = 0
14881483
result.append(name)
14891484
help_width = formatter.width - help_position
14901485
help_lines = textwrap.wrap(subcommand.help, help_width)
14911486
help_line = help_lines[0] if help_lines else ""
1492-
result.append("%*s%s\n" % (indent_first, "", help_line))
1487+
result.append(f"{' ' * indent_first}{help_line}\n")
14931488
result.extend(
1494-
[
1495-
"%*s%s\n" % (help_position, "", line)
1496-
for line in help_lines[1:]
1497-
]
1489+
[f"{' ' * help_position}{line}\n" for line in help_lines[1:]]
14981490
)
14991491
formatter.dedent()
15001492

beets/ui/commands.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -146,13 +146,13 @@ def _print_rows(names):
146146

147147
with lib.transaction() as tx:
148148
# The SQL uses the DISTINCT to get unique values from the query
149-
unique_fields = "SELECT DISTINCT key FROM (%s)"
149+
unique_fields = "SELECT DISTINCT key FROM ({})"
150150

151151
print_("Item flexible attributes:")
152-
_print_keys(tx.query(unique_fields % library.Item._flex_table))
152+
_print_keys(tx.query(unique_fields.format(library.Item._flex_table)))
153153

154154
print_("Album flexible attributes:")
155-
_print_keys(tx.query(unique_fields % library.Album._flex_table))
155+
_print_keys(tx.query(unique_fields.format(library.Album._flex_table)))
156156

157157

158158
fields_cmd = ui.Subcommand(
@@ -1928,7 +1928,7 @@ def stats_func(lib, opts, args):
19281928

19291929

19301930
def show_version(lib, opts, args):
1931-
print_("beets version %s" % beets.__version__)
1931+
print_(f"beets version {beets.__version__}")
19321932
print_(f"Python version {python_version()}")
19331933
# Show plugins.
19341934
names = sorted(p.name for p in plugins.find_plugins())
@@ -1992,7 +1992,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm, inherit):
19921992
extra = ""
19931993

19941994
changed = ui.input_select_objects(
1995-
"Really modify%s" % extra,
1995+
f"Really modify{extra}",
19961996
changed,
19971997
lambda o: print_and_modify(o, mods, dels),
19981998
)
@@ -2170,7 +2170,7 @@ def isalbummoved(album):
21702170
else:
21712171
if confirm:
21722172
objs = ui.input_select_objects(
2173-
"Really %s" % act,
2173+
f"Really {act}",
21742174
objs,
21752175
lambda o: show_path_changes(
21762176
[(o.path, o.destination(basedir=dest))]
@@ -2463,22 +2463,18 @@ def completion_script(commands):
24632463
yield "_beet() {\n"
24642464

24652465
# Command names
2466-
yield " local commands='%s'\n" % " ".join(command_names)
2466+
yield f" local commands={' '.join(command_names)!r}\n"
24672467
yield "\n"
24682468

24692469
# Command aliases
2470-
yield " local aliases='%s'\n" % " ".join(aliases.keys())
2470+
yield f" local aliases={' '.join(aliases.keys())!r}\n"
24712471
for alias, cmd in aliases.items():
24722472
yield f" local alias__{alias.replace('-', '_')}={cmd}\n"
24732473
yield "\n"
24742474

24752475
# Fields
2476-
yield " fields='%s'\n" % " ".join(
2477-
set(
2478-
list(library.Item._fields.keys())
2479-
+ list(library.Album._fields.keys())
2480-
)
2481-
)
2476+
fields = library.Item._fields.keys() | library.Album._fields.keys()
2477+
yield f" fields={' '.join(fields)!r}\n"
24822478

24832479
# Command options
24842480
for cmd, opts in options.items():

beets/util/bluelet.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,7 @@ def spawn(coro):
559559
and child coroutines run concurrently.
560560
"""
561561
if not isinstance(coro, types.GeneratorType):
562-
raise ValueError("%s is not a coroutine" % coro)
562+
raise ValueError(f"{coro} is not a coroutine")
563563
return SpawnEvent(coro)
564564

565565

@@ -569,7 +569,7 @@ def call(coro):
569569
returns a value using end(), then this event returns that value.
570570
"""
571571
if not isinstance(coro, types.GeneratorType):
572-
raise ValueError("%s is not a coroutine" % coro)
572+
raise ValueError(f"{coro} is not a coroutine")
573573
return DelegationEvent(coro)
574574

575575

beets/util/functemplate.py

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def __init__(self, ident, original):
136136
self.original = original
137137

138138
def __repr__(self):
139-
return "Symbol(%s)" % repr(self.ident)
139+
return f"Symbol({self.ident!r})"
140140

141141
def evaluate(self, env):
142142
"""Evaluate the symbol in the environment, returning a Unicode
@@ -178,7 +178,7 @@ def evaluate(self, env):
178178
except Exception as exc:
179179
# Function raised exception! Maybe inlining the name of
180180
# the exception will help debug.
181-
return "<%s>" % str(exc)
181+
return f"<{exc}>"
182182
return str(out)
183183
else:
184184
return self.original
@@ -224,7 +224,7 @@ def __init__(self, parts):
224224
self.parts = parts
225225

226226
def __repr__(self):
227-
return "Expression(%s)" % (repr(self.parts))
227+
return f"Expression({self.parts!r})"
228228

229229
def evaluate(self, env):
230230
"""Evaluate the entire expression in the environment, returning
@@ -296,9 +296,6 @@ def __init__(self, string, in_argument=False):
296296
GROUP_CLOSE,
297297
ESCAPE_CHAR,
298298
)
299-
special_char_re = re.compile(
300-
r"[%s]|\Z" % "".join(re.escape(c) for c in special_chars)
301-
)
302299
escapable_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_CLOSE, ARG_SEP)
303300
terminator_chars = (GROUP_CLOSE,)
304301

@@ -310,24 +307,18 @@ def parse_expression(self):
310307
"""
311308
# Append comma (ARG_SEP) to the list of special characters only when
312309
# parsing function arguments.
313-
extra_special_chars = ()
314-
special_char_re = self.special_char_re
315-
if self.in_argument:
316-
extra_special_chars = (ARG_SEP,)
317-
special_char_re = re.compile(
318-
r"[%s]|\Z"
319-
% "".join(
320-
re.escape(c)
321-
for c in self.special_chars + extra_special_chars
322-
)
323-
)
310+
extra_special_chars = (ARG_SEP,) if self.in_argument else ()
311+
special_chars = (*self.special_chars, *extra_special_chars)
312+
special_char_re = re.compile(
313+
rf"[{''.join(map(re.escape, special_chars))}]|\Z"
314+
)
324315

325316
text_parts = []
326317

327318
while self.pos < len(self.string):
328319
char = self.string[self.pos]
329320

330-
if char not in self.special_chars + extra_special_chars:
321+
if char not in special_chars:
331322
# A non-special character. Skip to the next special
332323
# character, treating the interstice as literal text.
333324
next_pos = (

beets/util/units.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def human_seconds_short(interval):
1919
string.
2020
"""
2121
interval = int(interval)
22-
return "%i:%02i" % (interval // 60, interval % 60)
22+
return f"{interval // 60}:{interval % 60:02d}"
2323

2424

2525
def human_bytes(size):

beetsplug/bpd/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
PROTOCOL_VERSION = "0.16.0"
5353
BUFSIZE = 1024
5454

55-
HELLO = "OK MPD %s" % PROTOCOL_VERSION
55+
HELLO = f"OK MPD {PROTOCOL_VERSION}"
5656
CLIST_BEGIN = "command_list_begin"
5757
CLIST_VERBOSE_BEGIN = "command_list_ok_begin"
5858
CLIST_END = "command_list_end"
@@ -1219,7 +1219,7 @@ def cmd_lsinfo(self, conn, path="/"):
12191219
if dirpath.startswith("/"):
12201220
# Strip leading slash (libmpc rejects this).
12211221
dirpath = dirpath[1:]
1222-
yield "directory: %s" % dirpath
1222+
yield f"directory: {dirpath}"
12231223

12241224
def _listall(self, basepath, node, info=False):
12251225
"""Helper function for recursive listing. If info, show

0 commit comments

Comments
 (0)