apply some f-string updates via flynt

This commit is contained in:
Damien Elmes 2021-10-02 23:51:42 +10:00
parent fe576a865d
commit 5801da13b3
15 changed files with 36 additions and 43 deletions

View file

@ -47,7 +47,7 @@ class DB:
res = self._db.execute(sql, a) res = self._db.execute(sql, a)
if self.echo: if self.echo:
# print a, ka # print a, ka
print(sql, "%0.3fms" % ((time.time() - t) * 1000)) print(sql, f"{(time.time() - t) * 1000:0.3f}ms")
if self.echo == "2": if self.echo == "2":
print(a, ka) print(a, ka)
return res return res
@ -57,7 +57,7 @@ class DB:
t = time.time() t = time.time()
self._db.executemany(sql, l) self._db.executemany(sql, l)
if self.echo: if self.echo:
print(sql, "%0.3fms" % ((time.time() - t) * 1000)) print(sql, f"{(time.time() - t) * 1000:0.3f}ms")
if self.echo == "2": if self.echo == "2":
print(l) print(l)
@ -65,7 +65,7 @@ class DB:
t = time.time() t = time.time()
self._db.commit() self._db.commit()
if self.echo: if self.echo:
print("commit %0.3fms" % ((time.time() - t) * 1000)) print(f"commit {(time.time() - t) * 1000:0.3f}ms")
def executescript(self, sql: str) -> None: def executescript(self, sql: str) -> None:
self.mod = True self.mod = True

View file

@ -234,9 +234,9 @@ class DeckManager(DeprecatedNamesMixin):
dids = set(dids) dids = set(dids)
if include_subdecks: if include_subdecks:
dids.update([child[1] for did in dids for child in self.children(did)]) dids.update([child[1] for did in dids for child in self.children(did)])
str_ids = ids2str(dids)
count = self.col.db.scalar( count = self.col.db.scalar(
"select count() from cards where did in {0} or " f"select count() from cards where did in {str_ids} or odid in {str_ids}"
"odid in {0}".format(ids2str(dids))
) )
return count return count

View file

@ -149,7 +149,7 @@ acq_reps+ret_reps, lapses, card_type_id from cards"""
mm = self.col.models mm = self.col.models
t = mm.new_template("Back") t = mm.new_template("Back")
t["qfmt"] = "{{Back}}" t["qfmt"] = "{{Back}}"
t["afmt"] = t["qfmt"] + "\n\n<hr id=answer>\n\n{{Front}}" # type: ignore t["afmt"] = f"{t['qfmt']}\n\n<hr id=answer>\n\n{{{{Front}}}}" # type: ignore
mm.add_template(m, t) mm.add_template(m, t)
self._addFronts(notes, m) self._addFronts(notes, m)
@ -161,19 +161,15 @@ acq_reps+ret_reps, lapses, card_type_id from cards"""
mm.addField(m, fm) mm.addField(m, fm)
t = mm.new_template("Recognition") t = mm.new_template("Recognition")
t["qfmt"] = "{{Expression}}" t["qfmt"] = "{{Expression}}"
t["afmt"] = ( t[
cast(str, t["qfmt"]) "afmt"
+ """\n\n<hr id=answer>\n\n\ ] = f"{cast(str, t['qfmt'])}\n\n<hr id=answer>\n\n{{{{Pronunciation}}}}<br>\n{{{{Meaning}}}}<br>\n{{{{Notes}}}}"
{{Pronunciation}}<br>\n{{Meaning}}<br>\n{{Notes}}"""
)
mm.add_template(m, t) mm.add_template(m, t)
t = mm.new_template("Production") t = mm.new_template("Production")
t["qfmt"] = "{{Meaning}}" t["qfmt"] = "{{Meaning}}"
t["afmt"] = ( t[
cast(str, t["qfmt"]) "afmt"
+ """\n\n<hr id=answer>\n\n\ ] = f"{cast(str, t['qfmt'])}\n\n<hr id=answer>\n\n{{{{Expression}}}}<br>\n{{{{Pronunciation}}}}<br>\n{{{{Notes}}}}"
{{Expression}}<br>\n{{Pronunciation}}<br>\n{{Notes}}"""
)
mm.add_template(m, t) mm.add_template(m, t)
mm.add(m) mm.add(m)
self._addFronts(notes, m, fields=("f", "p_1", "m_1", "n")) self._addFronts(notes, m, fields=("f", "p_1", "m_1", "n"))

View file

@ -214,7 +214,7 @@ class ModelManager(DeprecatedNamesMixin):
def ensure_name_unique(self, notetype: NotetypeDict) -> None: def ensure_name_unique(self, notetype: NotetypeDict) -> None:
existing_id = self.id_for_name(notetype["name"]) existing_id = self.id_for_name(notetype["name"])
if existing_id is not None and existing_id != notetype["id"]: if existing_id is not None and existing_id != notetype["id"]:
notetype["name"] += "-" + checksum(str(time.time()))[:5] notetype["name"] += f"-{checksum(str(time.time()))[:5]}"
def update_dict(self, notetype: NotetypeDict) -> OpChanges: def update_dict(self, notetype: NotetypeDict) -> OpChanges:
"Update a NotetypeDict. Caller will need to re-load notetype if new fields/cards added." "Update a NotetypeDict. Caller will need to re-load notetype if new fields/cards added."

View file

@ -71,10 +71,9 @@ else
end) end)
""" """
self.col.db.execute( self.col.db.execute(
""" f"""
update cards set did = odid, %s, update cards set did = odid, {queue},
due = (case when odue>0 then odue else due end), odue = 0, odid = 0, usn = ? where %s""" due = (case when odue>0 then odue else due end), odue = 0, odid = 0, usn = ? where {lim}""",
% (queue, lim),
self.col.usn(), self.col.usn(),
) )

View file

@ -381,9 +381,7 @@ limit %d"""
else: else:
# benchmarks indicate it's about 10x faster to search all decks # benchmarks indicate it's about 10x faster to search all decks
# with the index than scan the table # with the index than scan the table
extra = " and did in " + ids2str( extra = f" and did in {ids2str(d.id for d in self.col.decks.all_names_and_ids())}"
d.id for d in self.col.decks.all_names_and_ids()
)
# review cards in relearning # review cards in relearning
self.col.db.execute( self.col.db.execute(
f""" f"""

View file

@ -1141,7 +1141,7 @@ and (queue={QUEUE_TYPE_NEW} or (queue={QUEUE_TYPE_REV} and due<=?))""",
return self.col.tr.scheduling_end() return self.col.tr.scheduling_end()
s = self.col.format_timespan(ivl_secs, FormatTimeSpan.ANSWER_BUTTONS) s = self.col.format_timespan(ivl_secs, FormatTimeSpan.ANSWER_BUTTONS)
if ivl_secs < self.col.conf["collapseTime"]: if ivl_secs < self.col.conf["collapseTime"]:
s = "<" + s s = f"<{s}"
return s return s
def _is_finished(self) -> bool: def _is_finished(self) -> bool:

View file

@ -91,7 +91,7 @@ def htmlToTextLine(s: str) -> str:
def ids2str(ids: Iterable[Union[int, str]]) -> str: def ids2str(ids: Iterable[Union[int, str]]) -> str:
"""Given a list of integers, return a string '(int1,int2,...)'.""" """Given a list of integers, return a string '(int1,int2,...)'."""
return "(%s)" % ",".join(str(i) for i in ids) return f"({','.join(str(i) for i in ids)})"
def timestampID(db: DBProxy, table: str) -> int: def timestampID(db: DBProxy, table: str) -> int:

View file

@ -32,7 +32,7 @@ if __name__ == "__main__":
# strip off prefix # strip off prefix
for entry in sys.path: for entry in sys.path:
if "__mypy_" in entry: if "__mypy_" in entry:
typeshed = entry[4:] + "\\mypy\\typeshed" typeshed = f"{entry[4:]}\\mypy\\typeshed"
args.append("--custom-typeshed-dir") args.append("--custom-typeshed-dir")
args.append(typeshed) args.append(typeshed)

View file

@ -63,7 +63,7 @@ def test_anki2_mediadupes():
note.write("bar") note.write("bar")
imp = Anki2Importer(empty, col.path) imp = Anki2Importer(empty, col.path)
imp.run() imp.run()
assert sorted(os.listdir(empty.media.dir())) == ["foo.mp3", "foo_%s.mp3" % mid] assert sorted(os.listdir(empty.media.dir())) == ["foo.mp3", f"foo_{mid}.mp3"]
n = empty.get_note(empty.db.scalar("select id from notes")) n = empty.get_note(empty.db.scalar("select id from notes"))
assert "_" in n.fields[0] assert "_" in n.fields[0]
# if the localized media file already exists, we rewrite the note and # if the localized media file already exists, we rewrite the note and
@ -73,8 +73,8 @@ def test_anki2_mediadupes():
note.write("bar") note.write("bar")
imp = Anki2Importer(empty, col.path) imp = Anki2Importer(empty, col.path)
imp.run() imp.run()
assert sorted(os.listdir(empty.media.dir())) == ["foo.mp3", "foo_%s.mp3" % mid] assert sorted(os.listdir(empty.media.dir())) == ["foo.mp3", f"foo_{mid}.mp3"]
assert sorted(os.listdir(empty.media.dir())) == ["foo.mp3", "foo_%s.mp3" % mid] assert sorted(os.listdir(empty.media.dir())) == ["foo.mp3", f"foo_{mid}.mp3"]
n = empty.get_note(empty.db.scalar("select id from notes")) n = empty.get_note(empty.db.scalar("select id from notes"))
assert "_" in n.fields[0] assert "_" in n.fields[0]

View file

@ -93,7 +93,7 @@ def test_latex():
def _test_includes_bad_command(bad): def _test_includes_bad_command(bad):
col = getEmptyCol() col = getEmptyCol()
note = col.newNote() note = col.newNote()
note["Front"] = "[latex]%s[/latex]" % bad note["Front"] = f"[latex]{bad}[/latex]"
col.addNote(note) col.addNote(note)
q = without_unicode_isolation(note.cards()[0].question()) q = without_unicode_isolation(note.cards()[0].question())
return ("'%s' is not allowed on cards" % bad in q, "Card content: %s" % q) return (f"'{bad}' is not allowed on cards" in q, f"Card content: {q}")

View file

@ -910,7 +910,7 @@ def test_timing():
# add a few review cards, due today # add a few review cards, due today
for i in range(5): for i in range(5):
note = col.newNote() note = col.newNote()
note["Front"] = "num" + str(i) note["Front"] = f"num{str(i)}"
col.addNote(note) col.addNote(note)
c = note.cards()[0] c = note.cards()[0]
c.type = CARD_TYPE_REV c.type = CARD_TYPE_REV

View file

@ -1019,7 +1019,7 @@ def test_timing():
# add a few review cards, due today # add a few review cards, due today
for i in range(5): for i in range(5):
note = col.newNote() note = col.newNote()
note["Front"] = "num" + str(i) note["Front"] = f"num{str(i)}"
col.addNote(note) col.addNote(note)
c = note.cards()[0] c = note.cards()[0]
c.type = CARD_TYPE_REV c.type = CARD_TYPE_REV

View file

@ -36,7 +36,7 @@ class Hook:
types = [] types = []
for arg in self.args or []: for arg in self.args or []:
(name, type) = arg.split(":") (name, type) = arg.split(":")
type = '"' + type.strip() + '"' type = f'"{type.strip()}"'
types.append(type) types.append(type)
types_str = ", ".join(types) types_str = ", ".join(types)
return f"Callable[[{types_str}], {self.return_type or 'None'}]" return f"Callable[[{types_str}], {self.return_type or 'None'}]"
@ -60,7 +60,7 @@ class Hook:
return "hook" return "hook"
def classname(self) -> str: def classname(self) -> str:
return "_" + stringcase.pascalcase(self.full_name()) return f"_{stringcase.pascalcase(self.full_name())}"
def list_code(self) -> str: def list_code(self) -> str:
return f"""\ return f"""\
@ -126,7 +126,7 @@ class {self.classname()}:
# legacy support # legacy support
anki.hooks.runHook({self.legacy_args()}) anki.hooks.runHook({self.legacy_args()})
""" """
return out + "\n\n" return f"{out}\n\n"
def filter_fire_code(self) -> str: def filter_fire_code(self) -> str:
arg_names = self.arg_names() arg_names = self.arg_names()
@ -150,16 +150,16 @@ class {self.classname()}:
out += f"""\ out += f"""\
return {arg_names[0]} return {arg_names[0]}
""" """
return out + "\n\n" return f"{out}\n\n"
def write_file(path: str, hooks: List[Hook], prefix: str, suffix: str): def write_file(path: str, hooks: List[Hook], prefix: str, suffix: str):
hooks.sort(key=attrgetter("name")) hooks.sort(key=attrgetter("name"))
code = prefix + "\n" code = f"{prefix}\n"
for hook in hooks: for hook in hooks:
code += hook.code() code += hook.code()
code += "\n" + suffix code += f"\n{suffix}"
# work around issue with latest black # work around issue with latest black
if sys.platform == "win32" and "HOME" in os.environ: if sys.platform == "win32" and "HOME" in os.environ:

View file

@ -21,11 +21,11 @@ else:
subprocess.run( subprocess.run(
[ [
protoc, protoc,
"--plugin=protoc-gen-mypy=" + mypy_protobuf, f"--plugin=protoc-gen-mypy={mypy_protobuf}",
"--python_out=.", "--python_out=.",
"--mypy_out=.", "--mypy_out=.",
"-I" + prefix, f"-I{prefix}",
"-Iexternal/ankidesktop/" + prefix, f"-Iexternal/ankidesktop/{prefix}",
*protos, *protos,
], ],
# mypy prints to stderr on success :-( # mypy prints to stderr on success :-(