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 # Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html # 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): def fix_snakecase(name):
for fix in "a_v", "i_d": for fix in "a_v", "i_d":
name = re.sub( name = re.sub(
f"(\w)({fix})(\w)", fr"(\w)({fix})(\w)",
lambda m: m.group(1) + m.group(2).replace("_", "") + m.group(3), lambda m: m.group(1) + m.group(2).replace("_", "") + m.group(3),
name, name,
) )

View file

@ -547,7 +547,7 @@ class DeckManager:
return parents return parents
def nameMap(self) -> Dict[str, Deck]: 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 # Dynamic decks
########################################################################## ##########################################################################

View file

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

View file

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

View file

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

View file

@ -71,7 +71,7 @@ class TextImporter(NoteImporter):
def openFile(self) -> None: def openFile(self) -> None:
self.dialect = 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() self.data = self.fileobj.read()
def sub(s): def sub(s):

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -570,7 +570,9 @@ if isWin:
ret.result() ret.result()
except RuntimeError: except RuntimeError:
# fixme: i18n if this turns out to happen frequently # 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 return
# inject file into the top of the audio queue # inject file into the top of the audio queue

View file

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

View file

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