Skip to content

Commit

Permalink
use f-string equal syntax added in Python 3.8
Browse files Browse the repository at this point in the history
  • Loading branch information
ilius committed Sep 18, 2022
1 parent 8f7d7cf commit 2c58554
Show file tree
Hide file tree
Showing 39 changed files with 84 additions and 87 deletions.
4 changes: 2 additions & 2 deletions pyglossary/compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def compress(glos: "GlossaryType", filename: str, compression: str) -> str:
f"{e}\nFailed to compress file \"{filename}\""
)
else:
raise ValueError(f"unexpected compression={compression!r}")
raise ValueError(f"unexpected {compression=}")

if isfile(compFilename):
return compFilename
Expand All @@ -137,4 +137,4 @@ def uncompress(srcFilename: str, dstFilename: str, compression: str) -> None:
return

# TODO: if compression == "zip":
raise ValueError(f"unexpected compression={compression!r}")
raise ValueError(f"unexpected {compression=}")
2 changes: 1 addition & 1 deletion pyglossary/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ def windows_show_exception(*exc_info):

if getattr(sys, "frozen", False):
# PyInstaller frozen executable
log.info(f"sys.frozen = {sys.frozen}")
log.info(f"{sys.frozen = }")
rootDir = dirname(sys.executable)
uiDir = join(rootDir, "pyglossary", "ui")
else:
Expand Down
6 changes: 3 additions & 3 deletions pyglossary/entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,17 +396,17 @@ def stripFullHtml(self) -> None:
word = self.s_word
i = defi.find('<body')
if i == -1:
log.warning(f"<body not found: word={word}")
log.warning(f"<body not found: {word=}")
return
defi = defi[i + 5:]
i = defi.find('>')
if i == -1:
log.error(f"'>' after <body not found: word={word}")
log.error(f"'>' after <body not found: {word=}")
return
defi = defi[i + 1:]
i = defi.find('</body')
if i == -1:
log.error(f"</body close not found: word={word}")
log.error(f"</body close not found: {word=}")
return
defi = defi[:i]
self._defi = defi
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/entry_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,5 +399,5 @@ def run(self, entry: BaseEntry) -> "Optional[BaseEntry]":
word = entry.s_word
if len(word) > 30:
word = word[:37] + "..."
log.trace(f"MaxMemUsage: {usage}, word={word}")
log.trace(f"MaxMemUsage: {usage}, {word=}")
return entry
12 changes: 6 additions & 6 deletions pyglossary/glossary.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,7 +705,7 @@ def sortWords(

namedSortKey = namedSortKeyByName.get(sortKeyName)
if namedSortKey is None:
log.critical(f"invalid sortKeyName = {sortKeyName!r}")
log.critical(f"invalid {sortKeyName = }")
return

if not sortEncoding:
Expand Down Expand Up @@ -946,7 +946,7 @@ def _resolveConvertSortParams(
sort = False

if direct and sqlite:
raise ValueError(f"Conflictng arguments: direct={direct}, sqlite={sqlite}")
raise ValueError(f"Conflictng arguments: {direct=}, {sqlite=}")

if not sort:
if direct is None:
Expand Down Expand Up @@ -990,7 +990,7 @@ def _resolveConvertSortParams(

namedSortKey = namedSortKeyByName.get(sortKeyName)
if namedSortKey is None:
log.critical(f"invalid sortKeyName = {sortKeyName!r}")
log.critical(f"invalid {sortKeyName = }")
return None

log.info(f"Using sortKeyName = {namedSortKey.name!r}")
Expand Down Expand Up @@ -1058,9 +1058,9 @@ def convert(
return

if readOptions:
log.info(f"readOptions = {readOptions}")
log.info(f"{readOptions = }")
if writeOptions:
log.info(f"writeOptions = {writeOptions}")
log.info(f"{writeOptions = }")

outputArgs = self.detectOutputFormat(
filename=outputFilename,
Expand Down Expand Up @@ -1147,7 +1147,7 @@ def progressInit(self, *args) -> None:

def progress(self, pos: int, total: int, unit: str = "entries") -> None:
if total == 0:
log.warning(f"pos={pos}, total={total}")
log.warning(f"{pos=}, {total=}")
return
self.ui.progress(
min(pos + 1, total) / total,
Expand Down
14 changes: 7 additions & 7 deletions pyglossary/glossary_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def iterInfo(self) -> "Iterator[Tuple[str, str]]":

def getInfo(self, key: str) -> str:
if not isinstance(key, str):
raise TypeError(f"invalid key={key!r}, must be str")
raise TypeError(f"invalid {key=}, must be str")
return self._info.get(
infoKeysAliasDict.get(key.lower(), key),
"",
Expand All @@ -66,7 +66,7 @@ def setInfo(self, key: str, value: "Optional[str]") -> None:
return

if not isinstance(key, str):
raise TypeError(f"invalid key={key!r}, must be str")
raise TypeError(f"invalid {key=}, must be str")

key = fixUtf8(key)
value = fixUtf8(str(value))
Expand Down Expand Up @@ -127,13 +127,13 @@ def targetLang(self) -> "Optional[Lang]":
@sourceLang.setter
def sourceLang(self, lang) -> None:
if not isinstance(lang, Lang):
raise TypeError(f"invalid lang={lang}, must be a Lang object")
raise TypeError(f"invalid {lang=}, must be a Lang object")
self._info[c_sourceLang] = lang.name

@targetLang.setter
def targetLang(self, lang) -> None:
if not isinstance(lang, Lang):
raise TypeError(f"invalid lang={lang}, must be a Lang object")
raise TypeError(f"invalid {lang=}, must be a Lang object")
self._info[c_targetLang] = lang.name

@property
Expand Down Expand Up @@ -196,14 +196,14 @@ def detectLangsFromName(self):

def checkPart(part: str):
for match in re.findall("\w\w\w*", part):
# print(f"match = {match!r}")
# print(f"{match = }")
lang = langDict[match]
if lang is None:
continue
langNames.append(lang.name)

for part in re.split("-| to ", name):
# print(f"part = {part!r}")
# print(f"{part = }")
checkPart(part)
if len(langNames) >= 2:
break
Expand All @@ -216,7 +216,7 @@ def checkPart(part: str):
return

if len(langNames) > 2:
log.warning(f"detectLangsFromName: langNames = {langNames!r}")
log.warning(f"detectLangsFromName: {langNames = }")

log.info(
f"Detected sourceLang={langNames[0]!r}, "
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/html_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ def build_name2codepoint_dict():
for key in sorted(name2str.keys(), key=lambda s: (s.lower(), s)):
value = name2str[key]
if len(value) > 1:
raise ValueError(f"value = {value!r}")
raise ValueError(f"{value = }")
print(f"\t\"{key}\": 0x{ord(value):0>4x}, # {value}")


Expand Down
2 changes: 1 addition & 1 deletion pyglossary/langs/writing_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ def _getWritingSystemFromText(st: str, start: int, end: int):
unicodeWords = unicodedata.name(c).split(' ')
except ValueError as e:
# if c not in string.whitespace:
# print(f"c={c!r}, {e}")
# print(f"{c=}, {e}")
continue
alias = unicodeWords[0]
ws = writingSystemByUnicode.get(alias)
Expand Down
8 changes: 3 additions & 5 deletions pyglossary/plugin_prop.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def optionsPropFromDict(optionsPropDict):
try:
prop = optionFromDict(propDict)
except Exception:
log.exception(f"name={name!r}, propDict={propDict}\n")
log.exception(f"{name=}, {propDict=}\n")
continue
props[name] = prop
return props
Expand Down Expand Up @@ -283,9 +283,7 @@ def getOptionsFromClass(self, rwclass):
default = getattr(rwclass, attrName)
if name not in optionsProp:
if not callable(default):
log.warning(
f"format={self.name}, attrName={attrName}, type={type(default)}"
)
log.warning(f"format={self.name}, {attrName=}, {type(default)=}")
continue
prop = optionsProp[name]
if prop.disabled:
Expand Down Expand Up @@ -442,5 +440,5 @@ def getExtraOptionsFromFunc(cls, func, format):
if name not in ("filename", "dirname"):
extraOptNames.append(name)
if extraOptNames:
log.warning(f"{format}: extraOptNames = {extraOptNames}")
log.warning(f"{format}: {extraOptNames = }")
return extraOptNames
2 changes: 1 addition & 1 deletion pyglossary/plugins/aard2_slob.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def __iter__(self):

ctype = blob.content_type.split(";")[0]
if ctype not in (MIME_HTML, MIME_TEXT):
log.debug(f"{word!r}: content_type={blob.content_type}")
log.debug(f"unknown {blob.content_type=} in {word=}")
if word.startswith("~/"):
word = word[2:]
yield self._glos.newDataEntry(word, blob.content)
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/plugins/appledict/_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def prepare_content_with_soup(

elif href.startswith(("phonetics", "help:phonetics")):
# for oxford9
log.debug(f"phonetics: tag={tag}")
log.debug(f"phonetics: {tag=}")
if tag.audio and "name" in tag.audio.attrs:
tag["onmousedown"] = f"this.lastChild.play(); return false;"
src_name = tag.audio["name"].replace("#", "_")
Expand Down
5 changes: 2 additions & 3 deletions pyglossary/plugins/appledict_bin.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,7 @@ def _readEntry(self, pos: int) -> "Tuple[BaseEntry, int]":
entryRoot = etree.fromstring(entryFull)
except etree.XMLSyntaxError as e:
log.error(
f"pos={pos}, len(buf)={len(self._buf)}, "
f"entryFull={entryFull!r}"
f"{pos=}, len(buf)={len(self._buf)}, {entryFull=}"
)
raise e
entryElems = entryRoot.xpath("/d:entry", namespaces=entryRoot.nsmap)
Expand Down Expand Up @@ -271,7 +270,7 @@ def readEntryIds(self):
continue
id_i = b_entry.find(b'id="')
if id_i < 0:
log.error(f"id not found: {b_entry}, pos={pos}, buf={self._buf}")
log.error(f"id not found: {b_entry}, {pos=}, buf={self._buf}")
continue
id_j = b_entry.find(b'"', id_i + 4)
if id_j < 0:
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/plugins/cc_cedict/conv.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def make_entry(trad, simp, pinyin, eng, traditional_title):

def colorize(hf, syllables, tones):
if len(syllables) != len(tones):
log.warning(f"unmatched tones: syllables={syllables!r}, tones={tones}")
log.warning(f"unmatched tones: {syllables=}, {tones=}")
with hf.element("div", style="display: inline-block"):
for syllable in syllables:
with hf.element("font", color=""):
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/plugins/cc_kedict.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def _processEntry(
if self._spellKey and self._spellKey in edict:
spelling = edict[self._spellKey]
if not isinstance(spelling, str):
log.error(f"spelling = {spelling} type {type(spelling)}, edict={edict}")
log.error(f"{spelling=}, {type(spelling)=}, {edict=}")
if spelling is True:
# https://github.com/mhagiwara/cc-kedict/pull/1
spelling = "on"
Expand Down
4 changes: 2 additions & 2 deletions pyglossary/plugins/dicformids.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,8 @@ def write(self):
def writeBucket(dicIndex: int, entryList: "List[BaseEntry]"):
nonlocal dicMaxSize
log.debug(
f"dicIndex={dicIndex}, len(entryList)={len(entryList)}"
f", dicMaxSize={dicMaxSize}"
f"{dicIndex=}, {len(entryList)=}"
f", {dicMaxSize=}"
)
dicFp = open(join(
self._dirname,
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/plugins/dict_org.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def __iter__(self) -> "Iterator[BaseEntry]":
defi = b_defi.decode("utf_8", 'ignore')
defi = self.prettifyDefinitionText(defi)
except Exception as e:
log.error(f"b_defi = {b_defi}")
log.error(f"{b_defi = }")
raise e
yield self._glos.newEntry(word, defi)

Expand Down
4 changes: 2 additions & 2 deletions pyglossary/plugins/freedict.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,12 +661,12 @@ def setWordCount(self, header):
return
extent = extent_elem.text
if not extent.endswith(" headwords"):
log.warning(f"unexpected extent={extent}")
log.warning(f"unexpected {extent=}")
return
try:
self._wordCount = int(extent.split(" ")[0].replace(",", ""))
except Exception:
log.exception(f"unexpected extent={extent}")
log.exception(f"unexpected {extent=}")

def tostring(self, elem: "lxml.etree.Element") -> str:
from lxml import etree as ET
Expand Down
4 changes: 2 additions & 2 deletions pyglossary/plugins/html_dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ def navBar() -> str:
tailSize = len(self._tail.encode(encoding))

if max_file_size < len(header) + tailSize:
raise ValueError(f"max_file_size={max_file_size} is too small")
raise ValueError(f"{max_file_size=} is too small")

max_file_size -= tailSize

Expand Down Expand Up @@ -421,7 +421,7 @@ def addLinks(text: str, pos: int) -> str:
continue

if entry.defi.startswith('<!DOCTYPE html>') and defiFormat != "h":
log.error(f"bad defiFormat={defiFormat}")
log.error(f"bad {defiFormat=}")
defiFormat = "h"

entry.detectDefiFormat()
Expand Down
8 changes: 4 additions & 4 deletions pyglossary/plugins/iupac_goldbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def __iter__(self) -> "Iterator[BaseEntry]":
_id = elem.attrib.get("id")
termE = elem.find("./term")
if termE is None:
log.warning(f"no term, code={code}, id={_id}")
log.warning(f"no term, {code=}, {_id=}")
continue

term = self.getTerm(termE)
Expand Down Expand Up @@ -197,7 +197,7 @@ def __iter__(self) -> "Iterator[BaseEntry]":
replacedbyCode = replacedby.split(".")[-1]
replacedbyTerm = termByCode.get(replacedbyCode)
if replacedbyTerm is None:
log.warning(f"{term}: replacedby={replacedby}")
log.warning(f"{term}: {replacedby=}")
replacedbyTerm = replacedbyCode
defiParts.append(
f'Replaced by: <a href="bword://{replacedbyTerm}">{replacedbyTerm}</a>'
Expand All @@ -211,7 +211,7 @@ def __iter__(self) -> "Iterator[BaseEntry]":
relatedCode = relatedURL.split("/")[-1]
relatedTerm = termByCode.get(relatedCode)
if not relatedTerm:
log.warning(f"{term}: related={relatedURL}")
log.warning(f"{term}: {relatedURL=}")
relatedTerm = relatedCode
relatedLinkList.append(
f'<a href="bword://{relatedTerm}">{relatedTerm}</a>'
Expand All @@ -232,7 +232,7 @@ def __iter__(self) -> "Iterator[BaseEntry]":
try:
defi = "<br/>".join(defiParts)
except Exception:
log.error(f"defiParts = {defiParts!r}")
log.error(f"{defiParts = }")
continue

yield glos.newEntry(
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/plugins/octopus_mdict_new/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def loadLinks(self):
"extracting links done, "
f"sizeof(linksDict)={sys.getsizeof(linksDict)}"
)
log.info(f"wordCount = {wordCount}")
log.info(f"{wordCount = }")
self._linksDict = linksDict
self._wordCount = wordCount
self._mdx = MDX(self._filename, self._encoding, self._substyle)
Expand Down
Loading

0 comments on commit 2c58554

Please sign in to comment.