Skip to content

Commit dfd4b1d

Browse files
committed
Replace slightly more advanced attempts to use format calls
1 parent 2d6eeed commit dfd4b1d

File tree

10 files changed

+21
-29
lines changed

10 files changed

+21
-29
lines changed

CONTRIBUTING.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -246,8 +246,7 @@ There are a few coding conventions we use in beets:
246246
.. code-block:: python
247247
248248
with g.lib.transaction() as tx:
249-
rows = tx.query("SELECT DISTINCT '{0}' FROM '{1}' ORDER BY '{2}'"
250-
.format(field, model._table, sort_field))
249+
rows = tx.query(f"SELECT DISTINCT {field} FROM {model._table} ORDER BY {sort_field}")
251250
252251
To fetch Item objects from the database, use lib.items(…) and supply
253252
a query as an argument. Resist the urge to write raw SQL for your
@@ -261,7 +260,8 @@ There are a few coding conventions we use in beets:
261260
262261
Transaction objects help control concurrent access to the database
263262
and assist in debugging conflicting accesses.
264-
- ``str.format()`` should be used instead of the ``%`` operator
263+
- f-strings should be used instead of the ``%`` operator and ``str.format()``
264+
calls.
265265
- Never ``print`` informational messages; use the
266266
`logging <http://docs.python.org/library/logging.html>`__ module
267267
instead. In particular, we have our own logging shim, so you’ll see

beets/dbcore/query.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -848,20 +848,18 @@ def match(self, obj: Model) -> bool:
848848
date = datetime.fromtimestamp(timestamp)
849849
return self.interval.contains(date)
850850

851-
_clause_tmpl = "{0} {1} ?"
852-
853851
def col_clause(self) -> tuple[str, Sequence[SQLiteType]]:
854852
clause_parts = []
855853
subvals = []
856854

857855
# Convert the `datetime` objects to an integer number of seconds since
858856
# the (local) Unix epoch using `datetime.timestamp()`.
859857
if self.interval.start:
860-
clause_parts.append(self._clause_tmpl.format(self.field, ">="))
858+
clause_parts.append(f"{self.field} >= ?")
861859
subvals.append(int(self.interval.start.timestamp()))
862860

863861
if self.interval.end:
864-
clause_parts.append(self._clause_tmpl.format(self.field, "<"))
862+
clause_parts.append(f"{self.field} < ?")
865863
subvals.append(int(self.interval.end.timestamp()))
866864

867865
if clause_parts:

beets/dbcore/types.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ def __init__(self, digits: int):
194194
self.digits = digits
195195

196196
def format(self, value: int | N) -> str:
197-
return "{0:0{1}d}".format(value or 0, self.digits)
197+
return f"{value or 0:0{self.digits}d}"
198198

199199

200200
class PaddedInt(BasePaddedInt[int]):
@@ -249,7 +249,7 @@ def __init__(self, digits: int = 1):
249249
self.digits = digits
250250

251251
def format(self, value: float | N) -> str:
252-
return "{0:.{1}f}".format(value or 0, self.digits)
252+
return f"{value or 0:.{self.digits}f}"
253253

254254

255255
class Float(BaseFloat[float]):

beets/ui/commands.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,6 @@ def make_track_numbers(self, item, track_info):
488488
"""Format colored track indices."""
489489
cur_track = self.format_index(item)
490490
new_track = self.format_index(track_info)
491-
templ = "(#{})"
492491
changed = False
493492
# Choose color based on change.
494493
if cur_track != new_track:
@@ -500,10 +499,8 @@ def make_track_numbers(self, item, track_info):
500499
else:
501500
highlight_color = "text_faint"
502501

503-
cur_track = templ.format(cur_track)
504-
new_track = templ.format(new_track)
505-
lhs_track = ui.colorize(highlight_color, cur_track)
506-
rhs_track = ui.colorize(highlight_color, new_track)
502+
lhs_track = ui.colorize(highlight_color, f"(#{cur_track})")
503+
rhs_track = ui.colorize(highlight_color, f"(#{new_track})")
507504
return lhs_track, rhs_track, changed
508505

509506
@staticmethod

beetsplug/duplicates.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def _dup(lib, opts, args):
150150
count = self.config["count"].get(bool)
151151
delete = self.config["delete"].get(bool)
152152
remove = self.config["remove"].get(bool)
153-
fmt = self.config["format"].get(str)
153+
fmt_tmpl = self.config["format"].get(str)
154154
full = self.config["full"].get(bool)
155155
keys = self.config["keys"].as_str_seq()
156156
merge = self.config["merge"].get(bool)
@@ -175,15 +175,14 @@ def _dup(lib, opts, args):
175175
return
176176

177177
if path:
178-
fmt = "$path"
178+
fmt_tmpl = "$path"
179179

180180
# Default format string for count mode.
181-
if count and not fmt:
181+
if count and not fmt_tmpl:
182182
if album:
183-
fmt = "$albumartist - $album"
183+
fmt_tmpl = "$albumartist - $album"
184184
else:
185-
fmt = "$albumartist - $album - $title"
186-
fmt += ": {0}"
185+
fmt_tmpl = "$albumartist - $album - $title"
187186

188187
if checksum:
189188
for i in items:
@@ -207,7 +206,7 @@ def _dup(lib, opts, args):
207206
delete=delete,
208207
remove=remove,
209208
tag=tag,
210-
fmt=fmt.format(obj_count),
209+
fmt=f"{fmt_tmpl}: {obj_count}",
211210
)
212211

213212
self._command.func = _dup

beetsplug/info.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,6 @@ def print_data(data, item=None, fmt=None):
117117
return
118118

119119
maxwidth = max(len(key) for key in formatted)
120-
lineformat = f"{{0:>{maxwidth}}}: {{1}}"
121120

122121
if path:
123122
ui.print_(displayable_path(path))
@@ -126,7 +125,7 @@ def print_data(data, item=None, fmt=None):
126125
value = formatted[field]
127126
if isinstance(value, list):
128127
value = "; ".join(value)
129-
ui.print_(lineformat.format(field, value))
128+
ui.print_(f"{field:>{maxwidth}}: {value}")
130129

131130

132131
def print_data_keys(data, item=None):
@@ -139,12 +138,11 @@ def print_data_keys(data, item=None):
139138
if len(formatted) == 0:
140139
return
141140

142-
line_format = "{0}{{0}}".format(" " * 4)
143141
if path:
144142
ui.print_(displayable_path(path))
145143

146144
for field in sorted(formatted):
147-
ui.print_(line_format.format(field))
145+
ui.print_(f" {field}")
148146

149147

150148
class InfoPlugin(BeetsPlugin):

beetsplug/inline.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ def _compile_func(body):
3636
"""Given Python code for a function body, return a compiled
3737
callable that invokes that code.
3838
"""
39-
body = "def {}():\n {}".format(FUNC_NAME, body.replace("\n", "\n "))
39+
body = body.replace("\n", "\n ")
40+
body = f"def {FUNC_NAME}():\n {body}"
4041
code = compile(body, "inline", "exec")
4142
env = {}
4243
eval(code, env)

beetsplug/thumbnails.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def make_dolphin_cover_thumbnail(self, album):
202202
artfile = os.path.split(album.artpath)[1]
203203
with open(syspath(outfilename), "w") as f:
204204
f.write("[Desktop Entry]\n")
205-
f.write("Icon=./{}".format(artfile.decode("utf-8")))
205+
f.write(f"Icon=./{artfile.decode('utf-8')}")
206206
f.close()
207207
self._log.debug("Wrote file {0}", displayable_path(outfilename))
208208

test/plugins/test_random.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def experiment(field, histogram=False):
6969
# Print a histogram (useful for debugging).
7070
if histogram:
7171
for i in range(len(self.items)):
72-
print("{:2d} {}".format(i, "*" * positions.count(i)))
72+
print(f"{i:2d} {'*' * positions.count(i)}")
7373
return self._stats(positions)
7474

7575
mean1, stdev1, median1 = experiment("artist")

test/test_ui.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1261,7 +1261,6 @@ def test_album_data_change_wrap_newline(self):
12611261
msg = self._show_change(
12621262
cur_artist=long_name, cur_album="another album"
12631263
)
1264-
# _common.log.info("Message:{}".format(msg))
12651264
assert "artist: another artist" in msg
12661265
assert " -> the artist" in msg
12671266
assert "another album -> the album" not in msg

0 commit comments

Comments
 (0)