minor code cleanups with pyupgrade

- pyupgrade --py38-plus --keep-runtime-typing --keep-percent-format
- third-party mpv and winpaths excluded
This commit is contained in:
Damien Elmes 2021-02-11 09:37:38 +10:00
parent 4d373f4aa3
commit bb29ce88f3
40 changed files with 31 additions and 65 deletions

View file

@ -1,4 +1,3 @@
# -*- coding: UTF-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

View file

@ -77,7 +77,7 @@ def fullname(fullname):
def fix_snakecase(name):
for fix in "a_v", "i_d":
name = re.sub(
f"(\w)({fix})(\w)",
fr"(\w)({fix})(\w)",
lambda m: m.group(1) + m.group(2).replace("_", "") + m.group(3),
name,
)

View file

@ -547,7 +547,7 @@ class DeckManager:
return parents
def nameMap(self) -> Dict[str, Deck]:
return dict((d["name"], d) for d in self.all())
return {d["name"]: d for d in self.all()}
# Dynamic decks
##########################################################################

View file

@ -199,7 +199,7 @@ class AnkiExporter(Exporter):
# create a new collection at the target
try:
os.unlink(path)
except (IOError, OSError):
except OSError:
pass
self.dst = Collection(path)
self.src = self.col

View file

@ -78,7 +78,7 @@ class HttpClient:
def _agentName(self) -> str:
from anki import version
return "Anki {}".format(version)
return f"Anki {version}"
# allow user to accept invalid certs in work/school settings

View file

@ -409,7 +409,7 @@ insert or ignore into revlog values (?,?,?,?,?,?,?,?,?)""",
try:
with open(path, "rb") as f:
return f.read()
except (IOError, OSError):
except OSError:
return b""
def _srcMediaData(self, fname: str) -> bytes:
@ -425,7 +425,7 @@ insert or ignore into revlog values (?,?,?,?,?,?,?,?,?)""",
try:
with open(path, "wb") as f:
f.write(data)
except (OSError, IOError):
except OSError:
# the user likely used subdirectories
pass

View file

@ -71,7 +71,7 @@ class TextImporter(NoteImporter):
def openFile(self) -> None:
self.dialect = None
self.fileobj = open(self.file, "r", encoding="utf-8-sig")
self.fileobj = open(self.file, encoding="utf-8-sig")
self.data = self.fileobj.read()
def sub(s):

View file

@ -258,16 +258,11 @@ class SupermemoXmlImporter(NoteImporter):
# clean whitespaces
# set Capital letters for first char of the word
tmp = list(
set(
[
re.sub(r"(\[[0-9]+\])", " ", i).replace("_", " ")
for i in item.lTitle
]
)
{re.sub(r"(\[[0-9]+\])", " ", i).replace("_", " ") for i in item.lTitle}
)
tmp = list(set([re.sub(r"(\W)", " ", i) for i in tmp]))
tmp = list(set([re.sub("^[0-9 ]+$", "", i) for i in tmp]))
tmp = list(set([capwords(i).replace(" ", "") for i in tmp]))
tmp = list({re.sub(r"(\W)", " ", i) for i in tmp})
tmp = list({re.sub("^[0-9 ]+$", "", i) for i in tmp})
tmp = list({capwords(i).replace(" ", "") for i in tmp})
tags = [j[0].lower() + j[1:] for j in tmp if j.strip() != ""]
note.tags += tags
@ -310,13 +305,13 @@ class SupermemoXmlImporter(NoteImporter):
try:
return urllib.request.urlopen(source)
except (IOError, OSError):
except OSError:
pass
# try to open with native open function (if source is pathname)
try:
return open(source)
except (IOError, OSError):
except OSError:
pass
# treat source as string

View file

@ -287,7 +287,7 @@ class ModelManager:
def fieldMap(self, m: NoteType) -> Dict[str, Tuple[int, Field]]:
"Mapping of field name -> (ord, field)."
return dict((f["name"], (f["ord"], f)) for f in m["flds"])
return {f["name"]: (f["ord"], f) for f in m["flds"]}
def fieldNames(self, m: NoteType) -> List[str]:
return [f["name"] for f in m["flds"]]

View file

@ -243,7 +243,7 @@ def namedtmp(name: str, rm: bool = True) -> str:
if rm:
try:
os.unlink(path)
except (OSError, IOError):
except OSError:
pass
return path

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import platform
import time

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from typing import Any, Callable, List, Optional

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations
@ -819,7 +818,7 @@ class AddonsDialog(QDialog):
if not addon:
return
if re.match(r"^\d+$", addon):
openLink(aqt.appShared + "info/{}".format(addon))
openLink(aqt.appShared + f"info/{addon}")
else:
showWarning(tr(TR.ADDONS_ADDON_WAS_NOT_DOWNLOADED_FROM_ANKIWEB))
@ -865,7 +864,7 @@ class AddonsDialog(QDialog):
def onInstallFiles(self, paths: Optional[List[str]] = None) -> Optional[bool]:
if not paths:
key = tr(TR.ADDONS_PACKAGED_ANKI_ADDON) + " (*{})".format(self.mgr.ext)
key = tr(TR.ADDONS_PACKAGED_ANKI_ADDON) + f" (*{self.mgr.ext})"
paths_ = getFile(
self, tr(TR.ADDONS_INSTALL_ADDONS), None, key, key="addons", multi=True
)
@ -1158,9 +1157,7 @@ def _fetch_update_info_batch(
if resp.status_code == 200:
return resp.json()
else:
raise Exception(
"Unexpected response code from AnkiWeb: {}".format(resp.status_code)
)
raise Exception(f"Unexpected response code from AnkiWeb: {resp.status_code}")
def check_and_prompt_for_updates(

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations
@ -222,7 +221,7 @@ class DataModel(QAbstractTableModel):
def saveSelection(self) -> None:
cards = self.browser.selectedCards()
self.selectedCards = dict([(id, True) for id in cards])
self.selectedCards = {id: True for id in cards}
if getattr(self.browser, "card", None):
self.focusedCard = self.browser.card.id
else:

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import aqt

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from typing import Any

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from operator import itemgetter
from typing import Any, Dict, List, Optional

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from typing import Callable, List, Optional

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import aqt.editor
from aqt import gui_hooks

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import base64
@ -310,8 +309,8 @@ class Editor:
elif os.path.isabs(icon):
iconstr = self.resourceToData(icon)
else:
iconstr = "/_anki/imgs/{}.png".format(icon)
imgelm = """<img class=topbut src="{}">""".format(iconstr)
iconstr = f"/_anki/imgs/{icon}.png"
imgelm = f"""<img class=topbut src="{iconstr}">"""
else:
imgelm = ""
if label or not imgelm:
@ -319,7 +318,7 @@ class Editor:
else:
labelelm = ""
if id:
idstr = "id={}".format(id)
idstr = f"id={id}"
else:
idstr = ""
if toggleable:

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import html
import re

View file

@ -121,7 +121,7 @@ class ExportDialog(QDialog):
deck_name = self.decks[self.frm.deck.currentIndex()]
deck_name = re.sub('[\\\\/?<>:*|"^]', "_", deck_name)
filename = "{0}{1}".format(deck_name, self.exporter.ext)
filename = f"{deck_name}{self.exporter.ext}"
if callable(self.exporter.key):
key_str = self.exporter.key(self.col)
else:
@ -149,7 +149,7 @@ class ExportDialog(QDialog):
try:
f = open(file, "wb")
f.close()
except (OSError, IOError) as e:
except OSError as e:
showWarning(tr(TR.EXPORTING_COULDNT_SAVE_FILE, val=str(e)))
else:
os.unlink(file)

View file

@ -1,4 +1,3 @@
# coding=utf-8
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import json

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
"""

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations
@ -446,7 +445,7 @@ class AnkiQt(QMainWindow):
if getattr(w, "silentlyClose", None):
w.close()
else:
print("Window should have been closed: {}".format(w))
print(f"Window should have been closed: {w}")
def unloadProfileAndExit(self) -> None:
self.unloadProfile(self.cleanupAndExit)
@ -1447,7 +1446,7 @@ title="%s" %s>%s</button>""" % (
line = cursor.selectedText()
pfx, sfx = "pp(", ")"
if not line.startswith(pfx):
line = "{}{}{}".format(pfx, line, sfx)
line = f"{pfx}{line}{sfx}"
cursor.insertText(line)
cursor.setPosition(position + len(pfx))
frm.text.setTextCursor(cursor)

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from typing import List, Optional

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import anki.lang

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from typing import List, Optional

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations

View file

@ -570,7 +570,9 @@ if isWin:
ret.result()
except RuntimeError:
# fixme: i18n if this turns out to happen frequently
tooltip("TTS failed to play. Please check available languages in system settings.")
tooltip(
"TTS failed to play. Please check available languages in system settings."
)
return
# inject file into the top of the audio queue

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations
@ -531,7 +530,7 @@ def getSaveFile(
parent,
title,
path,
"{0} (*{1})".format(key, ext),
f"{key} (*{ext})",
options=QFileDialog.DontConfirmOverwrite,
)[0]
if file:

View file

@ -1,5 +1,4 @@
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import dataclasses
import json
@ -543,7 +542,7 @@ body {{ zoom: {zoom}; background: {background}; direction: {lang_dir}; {font} }}
elif name == "setHtml":
self._setHtml(*args)
else:
raise Exception("unknown action: {}".format(name))
raise Exception(f"unknown action: {name}")
def _openLinksExternally(self, url: str) -> None:
openLink(url)