Skip to content

Commit

Permalink
Use 'repr' and 'str' in place of '!r' and '!s'
Browse files Browse the repository at this point in the history
  • Loading branch information
Arav K. committed Jun 28, 2024
1 parent 721699a commit 9248e3d
Show file tree
Hide file tree
Showing 15 changed files with 46 additions and 38 deletions.
4 changes: 3 additions & 1 deletion beets/autotag/mb.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ def __init__(self, reason, verb, query, tb=None):
super().__init__(reason, verb, tb)

def get_message(self):
return f"{self._reasonstr()} in {self.verb} with query {self.query!r}"
return (
f"{self._reasonstr()} in {self.verb} with query {repr(self.query)}"
)


log = logging.getLogger("beets")
Expand Down
6 changes: 3 additions & 3 deletions beets/dbcore/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ def _awaken(

def __repr__(self) -> str:
name = type(self).__name__
fields = ", ".join(f"{k}={v!r}" for k, v in dict(self).items())
fields = ", ".join(f"{k}={repr(v)}" for k, v in dict(self).items())
return f"{name}({fields})"

def clear_dirty(self):
Expand Down Expand Up @@ -558,12 +558,12 @@ def __iter__(self) -> Iterator[str]:

def __getattr__(self, key):
if key.startswith("_"):
raise AttributeError(f"model has no attribute {key!r}")
raise AttributeError(f"model has no attribute {repr(key)}")
else:
try:
return self[key]
except KeyError:
raise AttributeError(f"no such field {key!r}")
raise AttributeError(f"no such field {repr(key)}")

def __setattr__(self, key, value):
if key.startswith("_"):
Expand Down
16 changes: 9 additions & 7 deletions beets/dbcore/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def match(self, obj: Model) -> bool:

def __repr__(self) -> str:
return (
f"{self.__class__.__name__}({self.field_name!r}, {self.pattern!r}, "
f"{self.__class__.__name__}({repr(self.field_name)}, {repr(self.pattern)}, "
f"fast={self.fast})"
)

Expand Down Expand Up @@ -210,7 +210,9 @@ def match(self, obj: Model) -> bool:
return obj.get(self.field_name) is None

def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.field_name!r}, {self.fast})"
return (
f"{self.__class__.__name__}({repr(self.field_name)}, {self.fast})"
)


class StringFieldQuery(FieldQuery[P]):
Expand Down Expand Up @@ -503,7 +505,7 @@ def clause_with_joiner(
return clause, subvals

def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.subqueries!r})"
return f"{self.__class__.__name__}({repr(self.subqueries)})"

def __eq__(self, other) -> bool:
return super().__eq__(other) and self.subqueries == other.subqueries
Expand Down Expand Up @@ -548,7 +550,7 @@ def match(self, obj: Model) -> bool:

def __repr__(self) -> str:
return (
f"{self.__class__.__name__}({self.pattern!r}, {self.fields!r}, "
f"{self.__class__.__name__}({repr(self.pattern)}, {repr(self.fields)}, "
f"{self.query_class.__name__})"
)

Expand Down Expand Up @@ -619,7 +621,7 @@ def match(self, obj: Model) -> bool:
return not self.subquery.match(obj)

def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.subquery!r})"
return f"{self.__class__.__name__}({repr(self.subquery)})"

def __eq__(self, other) -> bool:
return super().__eq__(other) and self.subquery == other.subquery
Expand Down Expand Up @@ -975,7 +977,7 @@ def sort(self, items):
return items

def __repr__(self):
return f"{self.__class__.__name__}({self.sorts!r})"
return f"{self.__class__.__name__}({repr(self.sorts)})"

def __hash__(self):
return hash(tuple(self.sorts))
Expand Down Expand Up @@ -1015,7 +1017,7 @@ def key(obj: Model) -> Any:
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}"
f"({self.field!r}, ascending={self.ascending!r})"
f"({repr(self.field)}, ascending={repr(self.ascending)})"
)

def __hash__(self) -> int:
Expand Down
6 changes: 3 additions & 3 deletions beets/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def col_clause(self):

def __repr__(self) -> str:
return (
f"{self.__class__.__name__}({self.field!r}, {self.pattern!r}, "
f"{self.__class__.__name__}({repr(self.field)}, {repr(self.pattern)}, "
f"fast={self.fast}, case_sensitive={self.case_sensitive})"
)

Expand Down Expand Up @@ -729,7 +729,7 @@ def __repr__(self):
# can even deadlock due to the database lock.
name = type(self).__name__
keys = self.keys(with_album=False)
fields = (f"{k}={self[k]!r}" for k in keys)
fields = (f"{k}={repr(self[k])}" for k in keys)
return f"{name}({', '.join(fields)})"

def keys(self, computed=False, with_album=True):
Expand Down Expand Up @@ -1572,7 +1572,7 @@ def parse_query_string(s, model_cls):
The string is split into components using shell-like syntax.
"""
message = f"Query is not unicode: {s!r}"
message = f"Query is not unicode: {repr(s)}"
assert isinstance(s, str), message
try:
parts = shlex.split(s)
Expand Down
12 changes: 6 additions & 6 deletions beets/test/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,34 +159,34 @@ class Assertions:

def assertExists(self, path): # noqa
self.assertTrue(
os.path.exists(syspath(path)), f"file does not exist: {path!r}"
os.path.exists(syspath(path)), f"file does not exist: {repr(path)}"
)

def assertNotExists(self, path): # noqa
self.assertFalse(
os.path.exists(syspath(path)), f"file exists: {path!r}"
os.path.exists(syspath(path)), f"file exists: {repr(path)}"
)

def assertIsFile(self, path): # noqa
self.assertExists(path)
self.assertTrue(
os.path.isfile(syspath(path)),
f"path exists, but is not a regular file: {path!r}",
f"path exists, but is not a regular file: {repr(path)}",
)

def assertIsDir(self, path): # noqa
self.assertExists(path)
self.assertTrue(
os.path.isdir(syspath(path)),
f"path exists, but is not a directory: {path!r}",
f"path exists, but is not a directory: {repr(path)}",
)

def assert_equal_path(self, a, b):
"""Check that two paths are equal."""
self.assertEqual(
util.normpath(a),
util.normpath(b),
f"paths are not equal: {a!r} and {b!r}",
f"paths are not equal: {repr(a)} and {repr(b)}",
)


Expand Down Expand Up @@ -294,7 +294,7 @@ def __init__(self, output=None):
def __str__(self):
msg = "Attempt to read with no input provided."
if self.output is not None:
msg += f" Output: {self.output!r}"
msg += f" Output: {repr(self.output)}"
return msg


Expand Down
2 changes: 1 addition & 1 deletion beets/ui/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def get_singleton_disambig_fields(info: hooks.TrackInfo) -> Sequence[str]:
out = []
chosen_fields = config["match"]["singleton_disambig_fields"].as_str_seq()
calculated_values = {
"index": f"Index {info.index!s}",
"index": f"Index {str(info.index)}",
"track_alt": f"Track {info.track_alt}",
"album": (
f"[{info.album}]"
Expand Down
2 changes: 1 addition & 1 deletion beets/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def _reasonstr(self):
elif hasattr(self.reason, "strerror"): # i.e., EnvironmentError
return self.reason.strerror
else:
return f'"{self.reason!s}"'
return f'"{str(self.reason)}"'

def get_message(self):
"""Create the human-readable description of the error, sans
Expand Down
2 changes: 1 addition & 1 deletion beets/util/functemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def __init__(self, ident, args, original):
self.original = original

def __repr__(self):
return f"Call({self.ident!r}, {self.args!r}, {self.original!r})"
return f"Call({repr(self.ident)}, {repr(self.args)}, {repr(self.original)})"

def evaluate(self, env):
"""Evaluate the function call in the environment, returning a
Expand Down
4 changes: 2 additions & 2 deletions beetsplug/bpd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1142,7 +1142,7 @@ def _item_info(self, item):
pass

for tagtype, field in self.tagtype_map.items():
info_lines.append(f"{tagtype}: {getattr(item, field)!s}")
info_lines.append(f"{tagtype}: {str(getattr(item, field))}")

return info_lines

Expand Down Expand Up @@ -1301,7 +1301,7 @@ def cmd_status(self, conn):

yield (
f"bitrate: {item.bitrate / 1000}",
f"audio: {item.samplerate!s}:{item.bitdepth!s}:{item.channels!s}",
f"audio: {str(item.samplerate)}:{str(item.bitdepth)}:{str(item.channels)}",
)

(pos, total) = self.player.time()
Expand Down
4 changes: 3 additions & 1 deletion beetsplug/edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ def edit(filename, log):
try:
subprocess.call(cmd)
except OSError as exc:
raise ui.UserError(f"could not run editor command {cmd[0]!r}: {exc}")
raise ui.UserError(
f"could not run editor command {repr(cmd[0])}: {exc}"
)


def dump(arg):
Expand Down
8 changes: 4 additions & 4 deletions beetsplug/replaygain.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ def _find_line(
if output[i].startswith(search):
return i
raise ReplayGainError(
f"ffmpeg output: missing {search!r} after line {start_line}"
f"ffmpeg output: missing {repr(search)} after line {start_line}"
)

def _parse_float(self, line: bytes) -> float:
Expand All @@ -547,7 +547,7 @@ def _parse_float(self, line: bytes) -> float:
parts = line.split(b":", 1)
if len(parts) < 2:
raise ReplayGainError(
f"ffmpeg output: expected key value pair, found {line!r}"
f"ffmpeg output: expected key value pair, found {repr(line)}"
)
value = parts[1].lstrip()
# strip unit
Expand All @@ -557,7 +557,7 @@ def _parse_float(self, line: bytes) -> float:
return float(value)
except ValueError:
raise ReplayGainError(
f"ffmpeg output: expected float value, found {value!r}"
f"ffmpeg output: expected float value, found {repr(value)}"
)


Expand Down Expand Up @@ -886,7 +886,7 @@ def _on_error(self, bus, message):
f = self._src.get_property("location")
# A GStreamer error, either an unsupported format or a bug.
self._error = ReplayGainError(
f"Error {err!r} - {debug!r} on file {f!r}"
f"Error {repr(err)} - {repr(debug)} on file {repr(f)}"
)

def _on_tag(self, bus, message):
Expand Down
4 changes: 3 additions & 1 deletion beetsplug/thumbnails.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,4 +292,6 @@ def uri(self, path):
try:
return uri.decode(util._fsencoding())
except UnicodeDecodeError:
raise RuntimeError(f"Could not decode filename from GIO: {uri!r}")
raise RuntimeError(
f"Could not decode filename from GIO: {repr(uri)}"
)
6 changes: 3 additions & 3 deletions test/plugins/test_lyrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,9 @@ def assertLyricsContentOk(self, title, text, msg=""): # noqa: N802

if not keywords <= words:
details = (
f"{keywords!r} is not a subset of {words!r}."
f" Words only in expected set {keywords - words!r},"
f" Words only in result set {words - keywords!r}."
f"{repr(keywords)} is not a subset of {repr(words)}."
f" Words only in expected set {repr(keywords - words)},"
f" Words only in result set {repr(words - keywords)}."
)
self.fail(f"{details} : {msg}")

Expand Down
6 changes: 3 additions & 3 deletions test/plugins/test_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def _parse_status(self, status):
cmd, rest = rest[2:].split("}")
return False, (int(code), int(pos), cmd, rest[1:])
else:
raise RuntimeError(f"Unexpected status: {status!r}")
raise RuntimeError(f"Unexpected status: {repr(status)}")

def _parse_body(self, body):
"""Messages are generally in the format "header: content".
Expand All @@ -145,7 +145,7 @@ def _parse_body(self, body):
if not line:
continue
if ":" not in line:
raise RuntimeError(f"Unexpected line: {line!r}")
raise RuntimeError(f"Unexpected line: {repr(line)}")
header, content = line.split(":", 1)
content = content.lstrip()
if header in repeated_headers:
Expand Down Expand Up @@ -191,7 +191,7 @@ def get_response(self, force_multi=None):
responses.append(MPCResponse(response))
response = b""
elif not line:
raise RuntimeError(f"Unexpected response: {line!r}")
raise RuntimeError(f"Unexpected response: {repr(line)}")

def serialise_command(self, command, *args):
cmd = [command.encode("utf-8")]
Expand Down
2 changes: 1 addition & 1 deletion test/plugins/test_thumbnails.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def exists(path):
return False
if path == syspath(LARGE_DIR):
return True
raise ValueError(f"unexpected path {path!r}")
raise ValueError(f"unexpected path {repr(path)}")

mock_os.path.exists = exists
plugin = ThumbnailsPlugin()
Expand Down

0 comments on commit 9248e3d

Please sign in to comment.