diff --git a/pyglossary/compression.py b/pyglossary/compression.py
index 1ef72f44f..4ca4737e0 100644
--- a/pyglossary/compression.py
+++ b/pyglossary/compression.py
@@ -69,9 +69,9 @@ def compressionOpen(
openFunc = compressionOpenFunc(ext)
if not openFunc:
raise RuntimeError(f"no compression found for {ext=}")
- _file = openFunc(filename, **kwargs)
- _file.compression = ext
- return _file
+ file = openFunc(filename, **kwargs)
+ file.compression = ext
+ return file
return open(filename, **kwargs) # noqa: SIM115
diff --git a/pyglossary/core.py b/pyglossary/core.py
index 6ede22c96..1a347d58e 100644
--- a/pyglossary/core.py
+++ b/pyglossary/core.py
@@ -111,31 +111,31 @@ def getDataDir() -> str:
if os.sep == "/":
return join(parent3, "share", "pyglossary")
- _dir = join(
+ dir_ = join(
parent3,
f"Python{sys.version_info.major}{sys.version_info.minor}",
"share",
"pyglossary",
)
- if isdir(_dir):
- return _dir
+ if isdir(dir_):
+ return dir_
- _dir = join(parent3, "Python3", "share", "pyglossary")
- if isdir(_dir):
- return _dir
+ dir_ = join(parent3, "Python3", "share", "pyglossary")
+ if isdir(dir_):
+ return dir_
- _dir = join(parent3, "Python", "share", "pyglossary")
- if isdir(_dir):
- return _dir
+ dir_ = join(parent3, "Python", "share", "pyglossary")
+ if isdir(dir_):
+ return dir_
- _dir = join(sys.prefix, "share", "pyglossary")
- if isdir(_dir):
- return _dir
+ dir_ = join(sys.prefix, "share", "pyglossary")
+ if isdir(dir_):
+ return dir_
if CONDA_PREFIX := os.getenv("CONDA_PREFIX"):
- _dir = join(CONDA_PREFIX, "share", "pyglossary")
- if isdir(_dir):
- return _dir
+ dir_ = join(CONDA_PREFIX, "share", "pyglossary")
+ if isdir(dir_):
+ return dir_
raise OSError("failed to detect dataDir")
diff --git a/pyglossary/ebook_base.py b/pyglossary/ebook_base.py
index 3190fcd7c..88acbb297 100644
--- a/pyglossary/ebook_base.py
+++ b/pyglossary/ebook_base.py
@@ -223,7 +223,7 @@ def write_css(self, custom_css_path_absolute: str) -> None:
def add_file_manifest(
self,
relative_path: str,
- _id: str,
+ id_: str,
contents: bytes,
mimetype: str,
) -> None:
@@ -231,7 +231,7 @@ def add_file_manifest(
self.manifest_files.append(
{
"path": relative_path,
- "id": _id,
+ "id": id_,
"mimetype": mimetype,
},
)
diff --git a/pyglossary/glossary_v2.py b/pyglossary/glossary_v2.py
index af4e108a7..39afec066 100644
--- a/pyglossary/glossary_v2.py
+++ b/pyglossary/glossary_v2.py
@@ -551,7 +551,7 @@ def wordTitleStr(
self,
word: str,
sample: str = "",
- _class: str = "",
+ class_: str = "",
) -> str:
"""
Return title tag for words.
@@ -573,8 +573,8 @@ def wordTitleStr(
if not sample:
sample = word
tag = self.titleTag(sample)
- if _class:
- return f'<{tag} class="{_class}">{word}{tag}>
'
+ if class_:
+ return f'<{tag} class="{class_}">{word}{tag}>
'
return f"<{tag}>{word}{tag}>
"
def getConfig(self, name: str, default: str | None) -> str | None:
diff --git a/pyglossary/logger.py b/pyglossary/logger.py
index c23b7eb02..60f63a092 100644
--- a/pyglossary/logger.py
+++ b/pyglossary/logger.py
@@ -135,8 +135,8 @@ def format_exception(
) -> str:
if exc_info is None:
exc_info = sys.exc_info()
- _type, value, tback = exc_info
- text = "".join(traceback.format_exception(_type, value, tback))
+ type_, value, tback = exc_info
+ text = "".join(traceback.format_exception(type_, value, tback))
if tback is None:
return text
@@ -182,10 +182,10 @@ def emit(self, record: logging.LogRecord) -> None:
msg = self.format(record)
###
if record.exc_info:
- _type, value, tback = record.exc_info
- if _type and tback and value: # to fix mypy error
+ type_, value, tback = record.exc_info
+ if type_ and tback and value: # to fix mypy error
tback_text = format_exception(
- exc_info=(_type, value, tback),
+ exc_info=(type_, value, tback),
add_locals=(self.level <= logging.DEBUG),
add_globals=False,
)
@@ -220,16 +220,16 @@ def setupLogging() -> Logger:
if os.sep == "\\":
def _windows_show_exception(
- _type: type[BaseException],
+ type_: type[BaseException],
exc: BaseException,
tback: TracebackType | None,
) -> None:
- if not (_type and exc and tback):
+ if not (type_ and exc and tback):
return
import ctypes
msg = format_exception(
- exc_info=(_type, exc, tback),
+ exc_info=(type_, exc, tback),
add_locals=(log.level <= logging.DEBUG),
add_globals=False,
)
@@ -241,15 +241,15 @@ def _windows_show_exception(
else:
def _unix_show_exception(
- _type: type[BaseException],
+ type_: type[BaseException],
exc: BaseException,
tback: TracebackType | None,
) -> None:
- if not (_type and exc and tback):
+ if not (type_ and exc and tback):
return
log.critical(
format_exception(
- exc_info=(_type, exc, tback),
+ exc_info=(type_, exc, tback),
add_locals=(log.level <= logging.DEBUG),
add_globals=False,
),
diff --git a/pyglossary/plugin_prop.py b/pyglossary/plugin_prop.py
index db1a3f849..62ff01d99 100644
--- a/pyglossary/plugin_prop.py
+++ b/pyglossary/plugin_prop.py
@@ -205,7 +205,7 @@ def module(self) -> Any:
moduleName = self._moduleName
log.debug(f"importing {moduleName} in DictPluginProp")
try:
- _mod = __import__(
+ mod = __import__(
f"pyglossary.plugins.{moduleName}",
fromlist=moduleName,
)
@@ -221,9 +221,9 @@ def module(self) -> Any:
# self._mod = _mod
if core.isDebug():
- self.checkModule(_mod)
+ self.checkModule(mod)
- return _mod
+ return mod
@property
def lname(self) -> str:
@@ -440,8 +440,8 @@ def checkModuleMore(self, module) -> None:
name = self.name
if not hasattr(module, "__all__"):
raise PluginCheckError(f"Please add __all__ to plugin {name!r}")
- _all = module.__all__
- for attr in _all:
+ all_ = module.__all__
+ for attr in all_:
if not hasattr(module, attr):
raise PluginCheckError(
f"Undefined name {attr!r} in __all__ in plugin {name!r}"
diff --git a/pyglossary/plugins/aard2_slob.py b/pyglossary/plugins/aard2_slob.py
index f0d4f6579..40bfcbc35 100644
--- a/pyglossary/plugins/aard2_slob.py
+++ b/pyglossary/plugins/aard2_slob.py
@@ -209,11 +209,11 @@ def __iter__(self) -> Iterator[EntryType | None]:
# are not all consecutive. so we have to keep a set of blob IDs
for blob in slobObj:
- _id = blob.identity
- if _id in blobSet:
+ id_ = blob.identity
+ if id_ in blobSet:
yield None # update progressbar
continue
- blobSet.add(_id)
+ blobSet.add(id_)
# blob.key is str, blob.content is bytes
word = blob.key
@@ -378,7 +378,7 @@ def addDataEntry(self, entry: EntryType) -> None:
def addEntry(self, entry: EntryType) -> None:
words = entry.l_word
b_defi = entry.defi.encode("utf-8")
- _ctype = self._content_type
+ ctype = self._content_type
writer = self._slobWriter
if writer is None:
raise ValueError("slobWriter is None")
@@ -412,19 +412,19 @@ def addEntry(self, entry: EntryType) -> None:
b_defi = b_defi.replace(b""" None:
writer.add(
b_defi,
headword,
- content_type=_ctype,
+ content_type=ctype,
)
for alt in alts:
writer.add(
b_defi,
f"{alt}, {headword}",
- content_type=_ctype,
+ content_type=ctype,
)
def write(self) -> Generator[None, EntryType, None]:
diff --git a/pyglossary/plugins/appledict/__init__.py b/pyglossary/plugins/appledict/__init__.py
index 3a421b3df..46c31e2b1 100644
--- a/pyglossary/plugins/appledict/__init__.py
+++ b/pyglossary/plugins/appledict/__init__.py
@@ -127,11 +127,11 @@ def loadBeautifulSoup() -> None:
import BeautifulSoup # type: ignore
except ImportError:
return
- _version: str = BeautifulSoup.__version__ # type: ignore
- if int(_version.split(".")[0]) < 4:
+ version: str = BeautifulSoup.__version__ # type: ignore
+ if int(version.split(".")[0]) < 4:
raise ImportError(
"BeautifulSoup is too old, required at least version 4, "
- f"{_version!r} found.\n"
+ f"{version!r} found.\n"
f"Please run `{pip} install lxml beautifulsoup4 html5lib`",
)
@@ -325,7 +325,7 @@ def write(self) -> Generator[None, EntryType, None]: # noqa: PLR0912
if not long_title:
continue
- _id = next(generate_id)
+ id_ = next(generate_id)
quoted_title = quote_string(long_title, BeautifulSoup)
content_title: str | None = long_title
@@ -335,7 +335,7 @@ def write(self) -> Generator[None, EntryType, None]: # noqa: PLR0912
content = prepare_content(content_title, defi, BeautifulSoup)
toFile.write(
- f'\n'
+ f'\n'
+ generate_indexes(long_title, alts, content, BeautifulSoup)
+ content
+ "\n\n",
@@ -361,12 +361,12 @@ def write(self) -> Generator[None, EntryType, None]: # noqa: PLR0912
).format(dict_name=fileNameBase),
)
- _copyright = glos.getInfo("copyright")
+ copyright_ = glos.getInfo("copyright")
if BeautifulSoup:
# strip html tags
- _copyright = str(
+ copyright_ = str(
BeautifulSoup.BeautifulSoup(
- _copyright,
+ copyright_,
features="lxml",
).text,
)
@@ -394,7 +394,7 @@ def write(self) -> Generator[None, EntryType, None]: # noqa: PLR0912
CFBundleIdentifier=bundle_id,
CFBundleDisplayName=glos.getInfo("name"),
CFBundleName=fileNameBase,
- DCSDictionaryCopyright=_copyright,
+ DCSDictionaryCopyright=copyright_,
DCSDictionaryManufacturerName=glos.author,
DCSDictionaryXSL=basename(xsl) if xsl else "",
DCSDictionaryDefaultPrefs=format_default_prefs(default_prefs),
diff --git a/pyglossary/plugins/appledict_bin/__init__.py b/pyglossary/plugins/appledict_bin/__init__.py
index 00ee12eb2..aa5fcb5ac 100644
--- a/pyglossary/plugins/appledict_bin/__init__.py
+++ b/pyglossary/plugins/appledict_bin/__init__.py
@@ -156,8 +156,8 @@ def fixLink(self, a: Element) -> Element:
# https://github.com/ilius/pyglossary/issues/343
id_i = len("x-dictionary:r:")
id_j = href.find(":", id_i)
- _id = href[id_i:id_j]
- title = self._titleById.get(_id)
+ id_ = href[id_i:id_j]
+ title = self._titleById.get(id_)
if title:
a.attrib["href"] = href = f"bword://{title}"
else:
@@ -294,9 +294,9 @@ def setMetadata(self, metadata: dict[str, Any]) -> None:
if identifier and identifier != name:
self._glos.setInfo("CFBundleIdentifier", identifier)
- _copyright = metadata.get("DCSDictionaryCopyright")
- if _copyright:
- self._glos.setInfo("copyright", _copyright)
+ copyright_ = metadata.get("DCSDictionaryCopyright")
+ if copyright_:
+ self._glos.setInfo("copyright", copyright_)
author = metadata.get("DCSDictionaryManufacturerName")
if author:
@@ -470,7 +470,7 @@ def readEntryIds(self) -> None:
if id_j < 0:
log.error(f"id closing not found: {entryBytes.decode(self._encoding)}")
continue
- _id = entryBytes[id_i + 4 : id_j].decode(self._encoding)
+ id_ = entryBytes[id_i + 4 : id_j].decode(self._encoding)
title_i = entryBytes.find(b'd:title="')
if title_i < 0:
log.error(f"title not found: {entryBytes.decode(self._encoding)}")
@@ -481,7 +481,7 @@ def readEntryIds(self) -> None:
f"title closing not found: {entryBytes.decode(self._encoding)}",
)
continue
- titleById[_id] = entryBytes[title_i + 9 : title_j].decode(self._encoding)
+ titleById[id_] = entryBytes[title_i + 9 : title_j].decode(self._encoding)
self._titleById = titleById
self._wordCount = len(titleById)
diff --git a/pyglossary/plugins/ayandict_sqlite.py b/pyglossary/plugins/ayandict_sqlite.py
index 7984b7edb..adb40fe34 100644
--- a/pyglossary/plugins/ayandict_sqlite.py
+++ b/pyglossary/plugins/ayandict_sqlite.py
@@ -189,7 +189,7 @@ def write(self) -> Generator[None, EntryType, None]:
cur = self._cur
if cur is None:
raise ValueError("cur is None")
- _hash = hashlib.md5()
+ hash_ = hashlib.md5()
while True:
entry = yield
if entry is None:
@@ -209,24 +209,24 @@ def write(self) -> Generator[None, EntryType, None]:
"INSERT INTO entry(term, article) VALUES (?, ?);",
(entry.l_word[0], defi),
)
- _id = cur.lastrowid
- if _id is None:
+ id_ = cur.lastrowid
+ if id_ is None:
raise ValueError("lastrowid is None")
for alt in entry.l_word[1:]:
cur.execute(
"INSERT INTO alt(id, term) VALUES (?, ?);",
- (_id, alt),
+ (id_, alt),
)
- _hash.update(entry.s_word.encode("utf-8"))
+ hash_.update(entry.s_word.encode("utf-8"))
if self._fuzzy:
- self.addFuzzy(_id, entry.l_word)
+ self.addFuzzy(id_, entry.l_word)
cur.execute(
"INSERT INTO meta (key, value) VALUES (?, ?);",
- ("hash", _hash.hexdigest()),
+ ("hash", hash_.hexdigest()),
)
- def addFuzzy(self, _id: int, terms: list[str]) -> None:
+ def addFuzzy(self, id_: int, terms: list[str]) -> None:
cur = self._cur
if cur is None:
raise ValueError("cur is None")
@@ -238,5 +238,5 @@ def addFuzzy(self, _id: int, terms: list[str]) -> None:
for sub in subs:
cur.execute(
"INSERT INTO fuzzy3(sub, term, id) VALUES (?, ?, ?);",
- (sub, term, _id),
+ (sub, term, id_),
)
diff --git a/pyglossary/plugins/babylon_bgl/bgl_reader.py b/pyglossary/plugins/babylon_bgl/bgl_reader.py
index bedaff2f8..a774f9b1a 100644
--- a/pyglossary/plugins/babylon_bgl/bgl_reader.py
+++ b/pyglossary/plugins/babylon_bgl/bgl_reader.py
@@ -793,12 +793,12 @@ def __iter__(self) -> Iterator[EntryType]: # noqa: PLR0912
yield self.readType2(block)
elif block.type == 11:
- succeed, _u_word, u_alts, u_defi = self.readEntry_Type11(block)
+ succeed, u_word, u_alts, u_defi = self.readEntry_Type11(block)
if not succeed:
continue
yield self._glos.newEntry(
- [_u_word] + u_alts,
+ [u_word] + u_alts,
u_defi,
)
@@ -1213,10 +1213,10 @@ def processKey(self, b_word: bytes) -> tuple[str, str]:
u_word = replaceHtmlEntriesInKeys(u_word)
# u_word = u_word.replace("
", "").replace("
", "")\
# .replace("
", "").replace("
", "")
- _u_word_copy = u_word
+ u_word_copy = u_word
u_word = stripHtmlTags(u_word)
- if u_word != _u_word_copy:
- u_word_html = _u_word_copy
+ if u_word != u_word_copy:
+ u_word_html = u_word_copy
# if(re.match(".*[&<>].*", _u_word_copy)):
# log.debug("original text: " + _u_word_copy + "\n" \
# + "new text: " + u_word + "\n")
diff --git a/pyglossary/plugins/babylon_bgl/bgl_reader_debug.py b/pyglossary/plugins/babylon_bgl/bgl_reader_debug.py
index a989d4e61..44ecd7366 100644
--- a/pyglossary/plugins/babylon_bgl/bgl_reader_debug.py
+++ b/pyglossary/plugins/babylon_bgl/bgl_reader_debug.py
@@ -53,14 +53,14 @@ def __init__(self) -> None:
class MetaDataBlock:
- def __init__(self, data: bytes, _type: str) -> None:
+ def __init__(self, data: bytes, type_: str) -> None:
self.data = data
- self.type = _type
+ self.type = type_
class MetaDataRange:
- def __init__(self, _type: str, count: int) -> None:
- self.type = _type
+ def __init__(self, type_: str, count: int) -> None:
+ self.type = type_
self.count = count
diff --git a/pyglossary/plugins/edict2/__init__.py b/pyglossary/plugins/edict2/__init__.py
index 44dca4fde..c95266eae 100644
--- a/pyglossary/plugins/edict2/__init__.py
+++ b/pyglossary/plugins/edict2/__init__.py
@@ -109,7 +109,7 @@ def __len__(self) -> int:
return 0
def __iter__(self) -> Iterator[EntryType]:
- _file = self.file
+ file = self.file
fileSize = self._fileSize
glos = self._glos
@@ -123,7 +123,7 @@ def __iter__(self) -> Iterator[EntryType]:
)
while True:
- line = _file.readline()
+ line = file.readline()
if not line:
break
line = line.rstrip("\n")
@@ -143,6 +143,6 @@ def __iter__(self) -> Iterator[EntryType]:
names,
article_text,
defiFormat="h",
- byteProgress=(_file.tell(), fileSize) if fileSize else None,
+ byteProgress=(file.tell(), fileSize) if fileSize else None,
)
yield entry
diff --git a/pyglossary/plugins/edlin.py b/pyglossary/plugins/edlin.py
index 94a8cf919..88d3470d2 100644
--- a/pyglossary/plugins/edlin.py
+++ b/pyglossary/plugins/edlin.py
@@ -228,13 +228,13 @@ def getEntryHash(self, entry: EntryType) -> str:
"""
from hashlib import sha1
- _hash = sha1(entry.s_word.encode("utf-8")).hexdigest()[:8] # noqa: S324
- if _hash not in self._hashSet:
- self._hashSet.add(_hash)
- return _hash
+ hash_ = sha1(entry.s_word.encode("utf-8")).hexdigest()[:8] # noqa: S324
+ if hash_ not in self._hashSet:
+ self._hashSet.add(hash_)
+ return hash_
index = 0
while True:
- tmp_hash = _hash + f"{index:x}"
+ tmp_hash = hash_ + f"{index:x}"
if tmp_hash not in self._hashSet:
self._hashSet.add(tmp_hash)
return tmp_hash
diff --git a/pyglossary/plugins/freedict/reader.py b/pyglossary/plugins/freedict/reader.py
index 2b205d5a8..cda46d229 100644
--- a/pyglossary/plugins/freedict/reader.py
+++ b/pyglossary/plugins/freedict/reader.py
@@ -271,12 +271,12 @@ def writeWithDirection(
else:
attrib["dir"] = "ltr"
try:
- _type = attrib.pop("type")
+ type_ = attrib.pop("type")
except KeyError:
pass
else:
- if _type != "trans":
- attrib["class"] = _type
+ if type_ != "trans":
+ attrib["class"] = type_
with hf.element(tag, attrib=attrib):
self.writeRichText(hf, child)
@@ -379,15 +379,15 @@ def writeSenseSense( # noqa: PLR0912
continue
if child.tag == f"{TEI}note":
- _type = child.attrib.get("type")
- if not _type:
+ type_ = child.attrib.get("type")
+ if not type_:
noteList.append(child)
- elif _type in {"pos", "gram"}:
+ elif type_ in {"pos", "gram"}:
gramList.append(child)
- elif _type in self.noteTypes:
+ elif type_ in self.noteTypes:
noteList.append(child)
else:
- log.warning(f"unknown note type {_type}")
+ log.warning(f"unknown note type {type_}")
noteList.append(child)
continue
@@ -599,17 +599,17 @@ def normalizeGramGrpChild(self, elem: Element) -> str: # noqa: PLR0912
if tag == f"{TEI}subc":
return self.subcMapping.get(text.lower(), text)
if tag == f"{TEI}gram":
- _type = elem.get("type")
- if _type:
- if _type == "pos":
+ type_ = elem.get("type")
+ if type_:
+ if type_ == "pos":
return self.posMapping.get(text.lower(), text)
- if _type == "gen":
+ if type_ == "gen":
return self.genderMapping.get(text.lower(), text)
- if _type in {"num", "number"}:
+ if type_ in {"num", "number"}:
return self.numberMapping.get(text.lower(), text)
- if _type == "subc":
+ if type_ == "subc":
return self.subcMapping.get(text.lower(), text)
- log.warning(f"unrecognize type={_type!r}: {self.tostring(elem)}")
+ log.warning(f"unrecognize type={type_!r}: {self.tostring(elem)}")
return text
log.warning(f" with no type: {self.tostring(elem)}")
@@ -690,18 +690,18 @@ def br() -> Element:
hf.write(br())
hf.write("\n")
- _hf = cast("T_htmlfile", hf)
- self.writeGramGroups(_hf, entry.findall("gramGrp", NAMESPACE))
- self.writeSenseList(_hf, senseList)
+ hf_ = cast("T_htmlfile", hf)
+ self.writeGramGroups(hf_, entry.findall("gramGrp", NAMESPACE))
+ self.writeSenseList(hf_, senseList)
defi = f.getvalue().decode("utf-8")
# defi = defi.replace("\xa0", " ") # do we need to do this?
- _file = self._file
+ file = self._file
return self._glos.newEntry(
keywords,
defi,
defiFormat="h",
- byteProgress=(_file.tell(), self._fileSize) if self._progress else None,
+ byteProgress=(file.tell(), self._fileSize) if self._progress else None,
)
def setWordCount(self, header: Element) -> None:
@@ -760,10 +760,10 @@ def setCopyright(self, header: Element) -> None:
if not elems:
log.warning("did not find copyright")
return
- _copyright = self.stripParagList(elems)
- _copyright = self.replaceRefLink(_copyright)
- self.setGlosInfo("copyright", _copyright)
- log.debug(f"Copyright: {_copyright!r}")
+ copyright_ = self.stripParagList(elems)
+ copyright_ = self.replaceRefLink(copyright_)
+ self.setGlosInfo("copyright", copyright_)
+ log.debug(f"Copyright: {copyright_!r}")
def setPublisher(self, header: Element) -> None:
elem = header.find(".//publisher", NAMESPACE)
diff --git a/pyglossary/plugins/gettext_po.py b/pyglossary/plugins/gettext_po.py
index 567095c72..938fdc0e3 100644
--- a/pyglossary/plugins/gettext_po.py
+++ b/pyglossary/plugins/gettext_po.py
@@ -102,13 +102,13 @@ def __iter__(self) -> Iterator[EntryType]: # noqa: PLR0912
exc_note(e, f"Run `{pip} install polib` to install")
raise
- _file = self._file
+ file = self._file
word = ""
defi = ""
msgstr = False
wordCount = 0
- for line in _file:
+ for line in file:
line = line.strip() # noqa: PLW2901
if not line:
continue
@@ -155,10 +155,10 @@ def __init__(self, glos: GlossaryType) -> None:
def open(self, filename: str) -> None:
self._filename = filename
- self._file = _file = open(filename, mode="w", encoding="utf-8")
- _file.write('#\nmsgid ""\nmsgstr ""\n')
+ self._file = file = open(filename, mode="w", encoding="utf-8")
+ file.write('#\nmsgid ""\nmsgstr ""\n')
for key, value in self._glos.iterInfo():
- _file.write(f'"{key}: {value}\\n"\n')
+ file.write(f'"{key}: {value}\\n"\n')
def finish(self) -> None:
self._filename = ""
@@ -172,7 +172,7 @@ def write(self) -> Generator[None, EntryType, None]:
exc_note(e, f"Run `{pip} install polib` to install")
raise
- _file = self._file
+ file = self._file
resources = self._resources
filename = self._filename
@@ -184,7 +184,7 @@ def write(self) -> Generator[None, EntryType, None]:
if resources:
entry.save(filename + "_res")
continue
- _file.write(
+ file.write(
f"msgid {po_escape(entry.s_word)}\n"
f"msgstr {po_escape(entry.defi)}\n\n",
)
diff --git a/pyglossary/plugins/html_dir.py b/pyglossary/plugins/html_dir.py
index 050f85258..9873ef959 100644
--- a/pyglossary/plugins/html_dir.py
+++ b/pyglossary/plugins/html_dir.py
@@ -216,11 +216,11 @@ def getLinksByFile(fileIndex: int) -> io.TextIOBase:
if targetFilename == filename:
continue
targetNew = f"{targetFilename}#entry{targetEntryIndex}"
- _file = getLinksByFile(int(fileIndexStr))
- _file.write(
+ file = getLinksByFile(int(fileIndexStr))
+ file.write(
f"{x_start}\t{x_size}\t{targetNew}\n",
)
- _file.flush()
+ file.flush()
linkTargetSet.clear()
del fileByWord, linkTargetSet
@@ -273,14 +273,14 @@ def getLinksByFile(fileIndex: int) -> io.TextIOBase:
)
continue
- _st = curLink.decode("utf-8")
- i = _st.find('href="#')
- j = _st.find('"', i + 7)
- word = _st[i + 7 : j]
+ st = curLink.decode("utf-8")
+ i = st.find('href="#')
+ j = st.find('"', i + 7)
+ word = st[i + 7 : j]
url = entry_url_fmt.format(word=word)
outFile.write(
(
- _st[:i] + f'class="broken" href="{url}"' + _st[j + 1 :]
+ st[:i] + f'class="broken" href="{url}"' + st[j + 1 :]
).encode("utf-8"),
)
@@ -452,7 +452,7 @@ def addLinks(text: str, pos: int) -> None:
self.writeInfo(filename, header)
- _word_title = self._word_title
+ word_title = self._word_title
resDir = self._resDir
entryIndex = -1
@@ -487,7 +487,7 @@ def addLinks(text: str, pos: int) -> None:
entryId = f"entry{entryIndex}"
- if _word_title:
+ if word_title:
words = [html.escape(word) for word in entry.l_word]
title = glos.wordTitleStr(
wordSep.join(words),
diff --git a/pyglossary/plugins/iupac_goldbook.py b/pyglossary/plugins/iupac_goldbook.py
index 848d07938..996923fba 100644
--- a/pyglossary/plugins/iupac_goldbook.py
+++ b/pyglossary/plugins/iupac_goldbook.py
@@ -81,12 +81,12 @@ def open(self, filename: str) -> None:
raise
self._filename = filename
- _file = compressionOpen(filename, mode="rb")
- _file.seek(0, 2)
- self._fileSize = _file.tell()
- _file.seek(0)
+ file = compressionOpen(filename, mode="rb")
+ file.seek(0, 2)
+ self._fileSize = file.tell()
+ file.seek(0)
- chunk = _file.read(800)
+ chunk = file.read(800)
chunk_end = chunk.find(b"")
chunk = chunk[:chunk_end]
chunk += b""
@@ -94,9 +94,9 @@ def open(self, filename: str) -> None:
infoRoot = ET.fromstring(chunk)
self.setMetadata(infoRoot)
- _file.seek(0)
+ file.seek(0)
context = ET.iterparse(
- _file,
+ file,
events=("end",),
tag="entry",
)
@@ -112,7 +112,7 @@ def open(self, filename: str) -> None:
termByCode[codeE.text] = term
self._termByCode = termByCode
- _file.close()
+ file.close()
def setGlosInfo(self, key: str, value: str) -> None:
if value is None:
@@ -197,7 +197,7 @@ def __iter__(self) -> Iterator[EntryType]: # noqa: PLR0912
fileSize = self._fileSize
termByCode = self._termByCode
- self._file = _file = compressionOpen(self._filename, mode="rb")
+ self._file = file = compressionOpen(self._filename, mode="rb")
context = ET.iterparse(
self._file,
events=("end",),
@@ -209,10 +209,10 @@ def __iter__(self) -> Iterator[EntryType]: # noqa: PLR0912
continue
code = codeE.text
- _id = elem.attrib.get("id")
+ id_ = elem.attrib.get("id")
termE = elem.find("./term")
if termE is None:
- log.warning(f"no term, {code=}, {_id=}")
+ log.warning(f"no term, {code=}, {id_=}")
continue
term = self.getTerm(termE)
@@ -303,7 +303,7 @@ def __iter__(self) -> Iterator[EntryType]: # noqa: PLR0912
words,
defi,
defiFormat="h",
- byteProgress=(_file.tell(), fileSize),
+ byteProgress=(file.tell(), fileSize),
)
# clean up preceding siblings to save memory
diff --git a/pyglossary/plugins/jmdict.py b/pyglossary/plugins/jmdict.py
index c3ea511ac..55be7c7e8 100644
--- a/pyglossary/plugins/jmdict.py
+++ b/pyglossary/plugins/jmdict.py
@@ -355,16 +355,16 @@ def br() -> Element:
hf.write(prop)
hf.write(br())
- _hf = cast("T_htmlfile", hf)
+ hf_ = cast("T_htmlfile", hf)
self.makeList(
- _hf,
+ hf_,
entry.findall("sense"),
self.writeSense,
)
defi = f.getvalue().decode("utf-8")
- _file = self._file
- byteProgress = (_file.tell(), self._fileSize)
+ file = self._file
+ byteProgress = (file.tell(), self._fileSize)
return self._glos.newEntry(
keywords,
defi,
diff --git a/pyglossary/plugins/jmnedict.py b/pyglossary/plugins/jmnedict.py
index 503af3054..71ad0b888 100644
--- a/pyglossary/plugins/jmnedict.py
+++ b/pyglossary/plugins/jmnedict.py
@@ -221,16 +221,16 @@ def br() -> Element:
hf.write(prop)
hf.write(br())
- _hf = cast("T_htmlfile", hf)
+ hf_ = cast("T_htmlfile", hf)
self.makeList(
- _hf,
+ hf_,
entry.findall("trans"),
self.writeTrans,
)
defi = f.getvalue().decode("utf-8")
- _file = self._file
- byteProgress = (_file.tell(), self._fileSize)
+ file = self._file
+ byteProgress = (file.tell(), self._fileSize)
return self._glos.newEntry(
keywords,
defi,
diff --git a/pyglossary/plugins/sql.py b/pyglossary/plugins/sql.py
index 2ba666821..99c31b96b 100644
--- a/pyglossary/plugins/sql.py
+++ b/pyglossary/plugins/sql.py
@@ -153,7 +153,7 @@ def write(self) -> Generator[None, EntryType, None]:
def fixStr(word: str) -> str:
return word.replace("'", "''").replace("\r", "").replace("\n", newline)
- _id = 1
+ id_ = 1
while True:
entry = yield
if entry is None:
@@ -165,13 +165,13 @@ def fixStr(word: str) -> str:
word = fixStr(words[0])
defi = fixStr(entry.defi)
fileObj.write(
- f"INSERT INTO word VALUES({_id}, '{word}', '{defi}');\n",
+ f"INSERT INTO word VALUES({id_}, '{word}', '{defi}');\n",
)
for alt in words[1:]:
fileObj.write(
- f"INSERT INTO alt VALUES({_id}, '{fixStr(alt)}');\n",
+ f"INSERT INTO alt VALUES({id_}, '{fixStr(alt)}');\n",
)
- _id += 1
+ id_ += 1
if self._transaction:
fileObj.write("END TRANSACTION;\n")
diff --git a/pyglossary/plugins/stardict/reader.py b/pyglossary/plugins/stardict/reader.py
index d0eabd3c9..9daa18d8d 100644
--- a/pyglossary/plugins/stardict/reader.py
+++ b/pyglossary/plugins/stardict/reader.py
@@ -213,7 +213,7 @@ def decodeRawDefiPart(
i_type: int,
unicode_errors: str,
) -> tuple[str, str]:
- _type = chr(i_type)
+ type_ = chr(i_type)
"""
_type: 'r'
@@ -233,27 +233,27 @@ def decodeRawDefiPart(
Use '/' character as directory separator.
"""
- _format = {
+ format_ = {
"m": "m",
"t": "m",
"y": "m",
"g": "h",
"h": "h",
"x": "x",
- }.get(_type, "")
+ }.get(type_, "")
- if not _format:
- log.warning(f"Definition type {_type!r} is not supported")
+ if not format_:
+ log.warning(f"Definition type {type_!r} is not supported")
- _defi = b_defiPart.decode("utf-8", errors=unicode_errors)
+ defi = b_defiPart.decode("utf-8", errors=unicode_errors)
# log.info(f"{_type}->{_format}: {_defi}".replace("\n", "")[:120])
- if _format == "x" and self._xdxf_to_html:
- _defi = self.xdxf_transform(_defi)
- _format = "h"
+ if format_ == "x" and self._xdxf_to_html:
+ defi = self.xdxf_transform(defi)
+ format_ = "h"
- return _format, _defi
+ return format_, defi
def renderRawDefiList(
self,
@@ -262,30 +262,30 @@ def renderRawDefiList(
) -> tuple[str, str]:
if len(rawDefiList) == 1:
b_defiPart, i_type = rawDefiList[0]
- _format, _defi = self.decodeRawDefiPart(
+ format_, defi = self.decodeRawDefiPart(
b_defiPart=b_defiPart,
i_type=i_type,
unicode_errors=unicode_errors,
)
- return _defi, _format
+ return defi, format_
defiFormatSet = set()
defisWithFormat = []
for b_defiPart, i_type in rawDefiList:
- _format, _defi = self.decodeRawDefiPart(
+ format_, defi = self.decodeRawDefiPart(
b_defiPart=b_defiPart,
i_type=i_type,
unicode_errors=unicode_errors,
)
- defisWithFormat.append((_defi, _format))
- defiFormatSet.add(_format)
+ defisWithFormat.append((defi, format_))
+ defiFormatSet.add(format_)
if len(defiFormatSet) == 1:
defis = [_defi for _defi, _ in defisWithFormat]
- _format = defiFormatSet.pop()
- if _format == "h":
- return "\n
".join(defis), _format
- return "\n".join(defis), _format
+ format_ = defiFormatSet.pop()
+ if format_ == "h":
+ return "\n
".join(defis), format_
+ return "\n".join(defis), format_
if not defiFormatSet:
log.error(f"empty defiFormatSet, {rawDefiList=}")
@@ -293,13 +293,14 @@ def renderRawDefiList(
# convert plaintext or xdxf to html
defis = []
- for _defi, _format in defisWithFormat:
- if _format == "m":
- _defi = _defi.replace("\n", "
")
- _defi = f"{_defi}
"
- elif _format == "x":
- _defi = self.xdxf_transform(_defi)
- defis.append(_defi)
+ for defi_, format_ in defisWithFormat:
+ defi = defi_
+ if format_ == "m":
+ defi = defi.replace("\n", "
")
+ defi = f"{defi}
"
+ elif format_ == "x":
+ defi = self.xdxf_transform(defi)
+ defis.append(defi)
return "\n
\n".join(defis), "h"
def __iter__(self) -> Iterator[EntryType]: # noqa: PLR0912
diff --git a/pyglossary/plugins/stardict/writer.py b/pyglossary/plugins/stardict/writer.py
index f4171f328..4ea5dd930 100644
--- a/pyglossary/plugins/stardict/writer.py
+++ b/pyglossary/plugins/stardict/writer.py
@@ -709,9 +709,9 @@ def writeIfoFile(
ifo.append(("synwordcount", str(synWordCount)))
desc = glos.getInfo("description")
- _copyright = glos.getInfo("copyright")
- if _copyright:
- desc = f"{_copyright}\n{desc}"
+ copyright_ = glos.getInfo("copyright")
+ if copyright_:
+ desc = f"{copyright_}\n{desc}"
publisher = glos.getInfo("publisher")
if publisher:
desc = f"Publisher: {publisher}\n{desc}"
diff --git a/pyglossary/plugins/stardict_textual.py b/pyglossary/plugins/stardict_textual.py
index 152ea4ed0..b14e18333 100644
--- a/pyglossary/plugins/stardict_textual.py
+++ b/pyglossary/plugins/stardict_textual.py
@@ -181,20 +181,21 @@ def renderDefiList(
if len(defiFormatSet) == 1:
defis = [_defi for _defi, _ in defisWithFormat]
- _format = defiFormatSet.pop()
- if _format == "h":
- return "\n
".join(defis), _format
- return "\n".join(defis), _format
+ format_ = defiFormatSet.pop()
+ if format_ == "h":
+ return "\n
".join(defis), format_
+ return "\n".join(defis), format_
# convert plaintext or xdxf to html
defis = []
- for _defi, _format in defisWithFormat:
- if _format == "m":
- _defi = _defi.replace("\n", "
")
- _defi = f"{_defi}
"
- elif _format == "x":
- _defi = self.xdxf_transform(_defi)
- defis.append(_defi)
+ for defi_, format_ in defisWithFormat:
+ defi = defi_
+ if format_ == "m":
+ defi = defi.replace("\n", "
")
+ defi = f"{defi}
"
+ elif format_ == "x":
+ defi = self.xdxf_transform(defi)
+ defis.append(defi)
return "\n
\n".join(defis), "h"
def __iter__(self) -> Iterator[EntryType]:
@@ -202,7 +203,7 @@ def __iter__(self) -> Iterator[EntryType]:
glos = self._glos
fileSize = self._fileSize
- self._file = _file = compressionOpen(self._filename, mode="rb")
+ self._file = file = compressionOpen(self._filename, mode="rb")
context = ET.iterparse( # type: ignore # noqa: PGH003
self._file,
events=("end",),
@@ -218,8 +219,8 @@ def __iter__(self) -> Iterator[EntryType]:
if child.tag in {"key", "synonym"}:
words.append(child.text)
elif child.tag == "definition":
- _type = child.attrib.get("type", "")
- if _type:
+ type_ = child.attrib.get("type", "")
+ if type_:
new_type = {
"m": "m",
"t": "m",
@@ -227,17 +228,17 @@ def __iter__(self) -> Iterator[EntryType]:
"g": "h",
"h": "h",
"x": "x",
- }.get(_type, "")
+ }.get(type_, "")
if not new_type:
- log.warning(f"unsupported definition type {_type}")
- _type = new_type
- if not _type:
- _type = "m"
- _defi = child.text.strip()
- if _type == "x" and self._xdxf_to_html:
- _defi = self.xdxf_transform(_defi)
- _type = "h"
- defisWithFormat.append((_defi, _type))
+ log.warning(f"unsupported definition type {type_}")
+ type_ = new_type
+ if not type_:
+ type_ = "m"
+ defi_ = child.text.strip()
+ if type_ == "x" and self._xdxf_to_html:
+ defi_ = self.xdxf_transform(defi_)
+ type_ = "h"
+ defisWithFormat.append((defi_, type_))
# TODO: child.tag == "definition-r"
else:
log.warning(f"unknown tag {child.tag}")
@@ -248,7 +249,7 @@ def __iter__(self) -> Iterator[EntryType]:
words,
defi,
defiFormat=defiFormat,
- byteProgress=(_file.tell(), fileSize),
+ byteProgress=(file.tell(), fileSize),
)
# clean up preceding siblings to save memory
@@ -298,9 +299,9 @@ def writeInfo(
glos = self._glos
desc = glos.getInfo("description")
- _copyright = glos.getInfo("copyright")
- if _copyright:
- desc = f"{_copyright}\n{desc}"
+ copyright_ = glos.getInfo("copyright")
+ if copyright_:
+ desc = f"{copyright_}\n{desc}"
publisher = glos.getInfo("publisher")
if publisher:
desc = f"Publisher: {publisher}\n{desc}"
@@ -315,8 +316,8 @@ def writeInfo(
maker.date(glos.getInfo("creationTime")),
maker.dicttype(""),
)
- _file = self._file
- _file.write(
+ file = self._file
+ file.write(
cast(
"bytes",
ET.tostring(
@@ -348,11 +349,11 @@ def write(self) -> Generator[None, EntryType, None]:
from lxml import builder
from lxml import etree as ET
- _file = self._file
+ file = self._file
encoding = self._encoding
maker = builder.ElementMaker()
- _file.write(
+ file.write(
"""
""",
@@ -397,7 +398,7 @@ def write(self) -> Generator[None, EntryType, None]:
# https://en.wiktionary.org/wiki/%CB%88#Translingual
self._file.write(articleStr + "\n")
- _file.write("")
+ file.write("")
if not os.listdir(self._resDir):
os.rmdir(self._resDir)
diff --git a/pyglossary/plugins/wiktextract.py b/pyglossary/plugins/wiktextract.py
index 9e6160e73..b1df0cb57 100644
--- a/pyglossary/plugins/wiktextract.py
+++ b/pyglossary/plugins/wiktextract.py
@@ -206,9 +206,9 @@ def br() -> Element:
hf.write(keyword)
hf.write(br())
- _hf = cast("T_htmlfile", hf)
+ hf_ = cast("T_htmlfile", hf)
- self.writeSoundList(_hf, data.get("sounds"))
+ self.writeSoundList(hf_, data.get("sounds"))
pos: str | None = data.get("pos")
if pos:
@@ -216,11 +216,11 @@ def br() -> Element:
with hf.element("font", color=self._gram_color):
hf.write(pos)
- self.writeSenseList(_hf, data.get("senses")) # type: ignore
+ self.writeSenseList(hf_, data.get("senses")) # type: ignore
- self.writeSynonyms(_hf, data.get("synonyms")) # type: ignore
+ self.writeSynonyms(hf_, data.get("synonyms")) # type: ignore
- self.writeAntonyms(_hf, data.get("antonyms")) # type: ignore
+ self.writeAntonyms(hf_, data.get("antonyms")) # type: ignore
# TODO: data.get("translations")
# list[dict[str, str]]
@@ -233,12 +233,12 @@ def br() -> Element:
defi = f.getvalue().decode("utf-8")
# defi = defi.replace("\xa0", " ") # do we need to do this?
- _file = self._file
+ file = self._file
return self._glos.newEntry(
keywords,
defi,
defiFormat="h",
- byteProgress=(_file.tell(), self._fileSize),
+ byteProgress=(file.tell(), self._fileSize),
)
def writeSoundPron(
@@ -370,9 +370,9 @@ def writeSenseExample( # noqa: PLR6301, PLR0912
) -> None:
# example keys: text, "english", "ref", "type"
textList: list[tuple[str, str]] = []
- _text = example.pop("example", "")
- if _text:
- textList.append((None, _text))
+ text_ = example.pop("example", "")
+ if text_:
+ textList.append((None, text_))
example.pop("ref", "")
example.pop("type", "")
diff --git a/pyglossary/plugins/xdxf_lax.py b/pyglossary/plugins/xdxf_lax.py
index 39fbe4880..f657fcc4c 100644
--- a/pyglossary/plugins/xdxf_lax.py
+++ b/pyglossary/plugins/xdxf_lax.py
@@ -116,17 +116,17 @@ def __init__(self, glos: GlossaryType) -> None:
)
def readUntil(self, untilByte: bytes) -> tuple[int, bytes]:
- _file = self._file
+ file = self._file
buf = b""
while True:
- tmp = _file.read(100)
+ tmp = file.read(100)
if not tmp:
break
buf += tmp
index = buf.find(untilByte)
if index < 0:
continue
- _file.seek(_file.tell() - len(buf) + index)
+ file.seek(file.tell() - len(buf) + index)
return index, buf[:index]
return -1, buf
@@ -150,10 +150,10 @@ def _readOneMetadata(self, tag: str, infoKey: str) -> None:
self._glos.setInfo(infoKey, elem.text)
def readMetadata(self) -> None:
- _file = self._file
- pos = _file.tell()
+ file = self._file
+ pos = file.tell()
self._readOneMetadata("full_name", "title")
- _file.seek(pos)
+ file.seek(pos)
self._readOneMetadata("description", "description")
def open(self, filename: str) -> None:
diff --git a/pyglossary/slob.py b/pyglossary/slob.py
index 5f1ac62be..64d159810 100644
--- a/pyglossary/slob.py
+++ b/pyglossary/slob.py
@@ -434,10 +434,10 @@ def read_byte_string(f: IOBase, len_spec: str) -> bytes:
class StructReader:
def __init__(
self,
- _file: IOBase,
+ file: IOBase,
encoding: str | None = None,
) -> None:
- self._file = _file
+ self._file = file
self.encoding = encoding
def read_int(self) -> int:
@@ -494,10 +494,10 @@ def flush(self) -> None:
class StructWriter:
def __init__(
self,
- _file: io.BufferedWriter,
+ file: io.BufferedWriter,
encoding: str | None = None,
) -> None:
- self._file = _file
+ self._file = file
self.encoding = encoding
def write_int(self, value: int) -> None:
@@ -577,19 +577,19 @@ def write(self, data: bytes) -> int:
return self._file.write(data)
-def read_header(_file: MultiFileReader) -> Header:
- _file.seek(0)
+def read_header(file: MultiFileReader) -> Header:
+ file.seek(0)
- magic = _file.read(len(MAGIC))
+ magic = file.read(len(MAGIC))
if magic != MAGIC:
raise UnknownFileFormat(f"magic {magic!r} != {MAGIC!r}")
- uuid = UUID(bytes=_file.read(16))
- encoding = read_byte_string(_file, U_CHAR).decode(UTF8)
+ uuid = UUID(bytes=file.read(16))
+ encoding = read_byte_string(file, U_CHAR).decode(UTF8)
if encodings.search_function(encoding) is None:
raise UnknownEncoding(encoding)
- reader = StructReader(_file, encoding)
+ reader = StructReader(file, encoding)
compression = reader.read_tiny_text()
if compression not in COMPRESSIONS:
raise UnknownCompression(compression)
@@ -932,13 +932,13 @@ class StoreItem(NamedTuple):
class Store(ItemList[StoreItem]):
def __init__(
self,
- _file: IOBase,
+ file: IOBase,
offset: int,
decompress: Callable[[bytes], bytes],
content_types: Sequence[str],
) -> None:
super().__init__(
- reader=StructReader(_file),
+ reader=StructReader(file),
offset=offset,
count_or_spec=U_INT,
pos_spec=U_LONG_LONG,
diff --git a/pyglossary/sort_modules/ebook.py b/pyglossary/sort_modules/ebook.py
index 5ec981168..2f3f1eb36 100644
--- a/pyglossary/sort_modules/ebook.py
+++ b/pyglossary/sort_modules/ebook.py
@@ -45,16 +45,16 @@ def getPrefix(words: list[str]) -> str:
def headword(words: list[str]) -> Any:
return words[0].encode(sortEncoding, errors="replace")
- _type = "TEXT" if sortEncoding == "utf-8" else "BLOB"
+ type_ = "TEXT" if sortEncoding == "utf-8" else "BLOB"
return [
(
"prefix",
- _type,
+ type_,
getPrefix,
),
(
"headword",
- _type,
+ type_,
headword,
),
]
diff --git a/pyglossary/sort_modules/stardict.py b/pyglossary/sort_modules/stardict.py
index 1c63c551f..d4536e36e 100644
--- a/pyglossary/sort_modules/stardict.py
+++ b/pyglossary/sort_modules/stardict.py
@@ -24,16 +24,16 @@ def headword_lower(words: list[str]) -> Any:
def headword(words: list[str]) -> Any:
return words[0].encode(sortEncoding, errors="replace")
- _type = "TEXT" if sortEncoding == "utf-8" else "BLOB"
+ type_ = "TEXT" if sortEncoding == "utf-8" else "BLOB"
return [
(
"headword_lower",
- _type,
+ type_,
headword_lower,
),
(
"headword",
- _type,
+ type_,
headword,
),
]
diff --git a/pyglossary/text_writer.py b/pyglossary/text_writer.py
index 2cb4919f9..66ad82cfc 100644
--- a/pyglossary/text_writer.py
+++ b/pyglossary/text_writer.py
@@ -106,7 +106,7 @@ def open(self, filename: str) -> None:
if not isdir(self._resDir):
os.mkdir(self._resDir)
- def _doWriteInfo(self, _file: io.TextIOBase) -> None:
+ def _doWriteInfo(self, file: io.TextIOBase) -> None:
entryFmt = self._entryFmt
outInfoKeysAliasDict = self._outInfoKeysAliasDict
wordEscapeFunc = self._wordEscapeFunc
@@ -128,7 +128,7 @@ def _doWriteInfo(self, _file: io.TextIOBase) -> None:
value = defiEscapeFunc(value) # noqa: PLW2901
if not value:
continue
- _file.write(
+ file.write(
entryFmt.format(
word=word,
defi=value,
@@ -139,7 +139,7 @@ def _open(self, filename: str) -> io.TextIOBase:
if not filename:
filename = self._glos.filename + self._ext
- _file = self._file = cast(
+ file = self._file = cast(
"io.TextIOBase",
c_open(
filename,
@@ -148,17 +148,17 @@ def _open(self, filename: str) -> io.TextIOBase:
newline=self._newline,
),
)
- _file.write(self._head)
+ file.write(self._head)
if self._writeInfo:
- self._doWriteInfo(_file)
+ self._doWriteInfo(file)
- _file.flush()
- return _file
+ file.flush()
+ return file
def write(self) -> Generator[None, EntryType, None]:
glos = self._glos
- _file = self._file
+ file = self._file
entryFmt = self._entryFmt
wordListEncodeFunc = self._wordListEncodeFunc
wordEscapeFunc = self._wordEscapeFunc
@@ -194,16 +194,16 @@ def write(self) -> Generator[None, EntryType, None]:
if defiEscapeFunc is not None:
defi = defiEscapeFunc(defi)
- _file.write(entryFmt.format(word=word, defi=defi))
+ file.write(entryFmt.format(word=word, defi=defi))
if file_size_approx > 0:
entryCount += 1
if (
entryCount % file_size_check_every == 0
- and _file.tell() >= file_size_approx
+ and file.tell() >= file_size_approx
):
fileIndex += 1
- _file = self._open(f"{self._filename}.{fileIndex}")
+ file = self._open(f"{self._filename}.{fileIndex}")
def finish(self) -> None:
if self._tail:
diff --git a/pyglossary/ui/argparse_main.py b/pyglossary/ui/argparse_main.py
index 7134fc7e3..a2224c93f 100644
--- a/pyglossary/ui/argparse_main.py
+++ b/pyglossary/ui/argparse_main.py
@@ -285,10 +285,10 @@ def validateFlags(args: argparse.Namespace, log: logging.Logger) -> bool:
return False
if args.sortKeyName and not lookupSortKey(args.sortKeyName):
- _valuesStr = ", ".join(_sk.name for _sk in namedSortKeyList)
+ valuesStr = ", ".join(_sk.name for _sk in namedSortKeyList)
log.critical(
f"Invalid sortKeyName={args.sortKeyName!r}"
- f". Supported values:\n{_valuesStr}",
+ f". Supported values:\n{valuesStr}",
)
return False
diff --git a/pyglossary/ui/ui_cmd_interactive.py b/pyglossary/ui/ui_cmd_interactive.py
index c0ee057ea..e42f175a9 100644
--- a/pyglossary/ui/ui_cmd_interactive.py
+++ b/pyglossary/ui/ui_cmd_interactive.py
@@ -391,10 +391,11 @@ def fs_ls(self, args: list[str]):
print(f"> List of directory {arg!r}:")
if not opts.long:
- for _path in os.listdir(arg):
- if isdir(_path):
- _path += "/"
- print(f"{_path}")
+ for path in os.listdir(arg):
+ if isdir(path):
+ print(f"{path}/")
+ else:
+ print(path)
continue
contents = os.listdir(arg)
@@ -432,18 +433,18 @@ def fs_cd(args: list[str]):
print(f"Changed current directory to: {newDir}")
def formatPromptMsg(self, level, msg, colon=":"):
- _indent = self.promptIndentStr * level
+ indent_ = self.promptIndentStr * level
if core.noColor:
- return f"{_indent} {msg}{colon} ", False
+ return f"{indent_} {msg}{colon} ", False
if self.promptIndentColor >= 0:
- _indent = f"\x1b[38;5;{self.promptIndentColor}m{_indent}{endFormat}"
+ indent_ = f"\x1b[38;5;{self.promptIndentColor}m{indent_}{endFormat}"
if self.promptMsgColor >= 0:
msg = f"\x1b[38;5;{self.promptMsgColor}m{msg}{endFormat}"
- return f"{_indent} {msg}{colon} ", True
+ return f"{indent_} {msg}{colon} ", True
def prompt(self, level, msg, colon=":", **kwargs):
msg, colored = self.formatPromptMsg(level, msg, colon)
diff --git a/pyglossary/ui/ui_gtk.py b/pyglossary/ui/ui_gtk.py
index 266866535..bd9c0fcf5 100644
--- a/pyglossary/ui/ui_gtk.py
+++ b/pyglossary/ui/ui_gtk.py
@@ -218,14 +218,14 @@ def onEntryChange(self, entry):
def setCursor(self, desc: str):
model = self.treev.get_model()
- _iter = model.iter_children(None)
- while _iter is not None:
- if model.get_value(_iter, 0) == desc:
- path = model.get_path(_iter)
+ iter_ = model.iter_children(None)
+ while iter_ is not None:
+ if model.get_value(iter_, 0) == desc:
+ path = model.get_path(iter_)
self.treev.set_cursor(path, self.descCol, False)
self.treev.scroll_to_cell(path)
return
- _iter = model.iter_next(_iter)
+ iter_ = model.iter_next(iter_)
def updateTree(self):
model = self.treev.get_model()
@@ -237,11 +237,11 @@ def updateTree(self):
self.setCursor(self.activeDesc)
def getActive(self) -> PluginProp | None:
- _iter = self.treev.get_selection().get_selected()[1]
- if _iter is None:
+ iter_ = self.treev.get_selection().get_selected()[1]
+ if iter_ is None:
return None
model = self.treev.get_model()
- desc = model.get_value(_iter, 0)
+ desc = model.get_value(iter_, 0)
return pluginByDesc[desc]
def setActive(self, plugin):
@@ -254,8 +254,8 @@ def setActive(self, plugin):
def rowActivated(self, treev, path, _col):
model = treev.get_model()
- _iter = model.get_iter(path)
- desc = model.get_value(_iter, 0)
+ iter_ = model.get_iter(path)
+ desc = model.get_value(iter_, 0)
self.activeDesc = desc
self.response(gtk.ResponseType.OK)
@@ -302,8 +302,8 @@ def getActive(self):
return ""
return self.activePlugin.name
- def setActive(self, _format):
- plugin = Glossary.plugins[_format]
+ def setActive(self, format_):
+ plugin = Glossary.plugins[format_]
self.activePlugin = plugin
self.set_label(plugin.description)
self.onChanged()
@@ -730,9 +730,9 @@ def emit(self, record):
# msg = msg.replace("\x00", "")
if record.exc_info:
- _type, value, tback = record.exc_info
+ type_, value, tback = record.exc_info
tback_text = "".join(
- traceback.format_exception(_type, value, tback),
+ traceback.format_exception(type_, value, tback),
)
if msg:
msg += "\n"
@@ -1028,8 +1028,8 @@ def status(self, msg):
# except KeyError:
# _id = self.statusMsgDict[msg] = self.statusNewId
# self.statusNewId += 1
- _id = self.statusBar.get_context_id(msg)
- self.statusBar.push(_id, msg)
+ id_ = self.statusBar.get_context_id(msg)
+ self.statusBar.push(id_, msg)
def __init__(
self,
diff --git a/pyglossary/ui/ui_gtk4.py b/pyglossary/ui/ui_gtk4.py
index 7dbb1f42e..2848733de 100644
--- a/pyglossary/ui/ui_gtk4.py
+++ b/pyglossary/ui/ui_gtk4.py
@@ -207,14 +207,14 @@ def onEntryChange(self, entry):
def setCursor(self, desc: str):
model = self.treev.get_model()
- _iter = model.iter_children(None)
- while _iter is not None:
- if model.get_value(_iter, 0) == desc:
- path = model.get_path(_iter)
+ iter_ = model.iter_children(None)
+ while iter_ is not None:
+ if model.get_value(iter_, 0) == desc:
+ path = model.get_path(iter_)
self.treev.set_cursor(path, self.descCol, False)
self.treev.scroll_to_cell(path)
return
- _iter = model.iter_next(_iter)
+ iter_ = model.iter_next(iter_)
def updateTree(self):
model = self.treev.get_model()
@@ -226,11 +226,11 @@ def updateTree(self):
self.setCursor(self.activeDesc)
def getActive(self) -> PluginProp | None:
- _iter = self.treev.get_selection().get_selected()[1]
- if _iter is None:
+ iter_ = self.treev.get_selection().get_selected()[1]
+ if iter_ is None:
return None
model = self.treev.get_model()
- desc = model.get_value(_iter, 0)
+ desc = model.get_value(iter_, 0)
return pluginByDesc[desc]
def setActive(self, plugin):
@@ -243,8 +243,8 @@ def setActive(self, plugin):
def rowActivated(self, treev, path, _col):
model = treev.get_model()
- _iter = model.get_iter(path)
- desc = model.get_value(_iter, 0)
+ iter_ = model.get_iter(path)
+ desc = model.get_value(iter_, 0)
self.activeDesc = desc
self.response(gtk.ResponseType.OK)
@@ -296,8 +296,8 @@ def getActive(self):
return ""
return self.activePlugin.name
- def setActive(self, _format):
- plugin = Glossary.plugins[_format]
+ def setActive(self, format_):
+ plugin = Glossary.plugins[format_]
self.activePlugin = plugin
self.set_label(plugin.description)
self.onChanged()
@@ -776,9 +776,9 @@ def emit(self, record):
# msg = msg.replace("\x00", "")
if record.exc_info:
- _type, value, tback = record.exc_info
+ type_, value, tback = record.exc_info
tback_text = "".join(
- traceback.format_exception(_type, value, tback),
+ traceback.format_exception(type_, value, tback),
)
if msg:
msg += "\n"
@@ -1091,8 +1091,8 @@ def status(self, msg):
# except KeyError:
# _id = self.statusMsgDict[msg] = self.statusNewId
# self.statusNewId += 1
- _id = self.statusBar.get_context_id(msg)
- self.statusBar.push(_id, msg)
+ id_ = self.statusBar.get_context_id(msg)
+ self.statusBar.push(id_, msg)
def __init__(
self,
diff --git a/pyglossary/ui/ui_tk.py b/pyglossary/ui/ui_tk.py
index 57ee4d488..0f31dc31d 100644
--- a/pyglossary/ui/ui_tk.py
+++ b/pyglossary/ui/ui_tk.py
@@ -176,9 +176,9 @@ def emit(self, record):
msg = self.format(record)
###
if record.exc_info:
- _type, value, tback = record.exc_info
+ type_, value, tback = record.exc_info
tback_text = "".join(
- traceback.format_exception(_type, value, tback),
+ traceback.format_exception(type_, value, tback),
)
if msg:
msg += "\n"
@@ -271,9 +271,9 @@ def __init__( # noqa: PLR0913
self.bind("", self.update)
self.canvas.pack(side="top", fill="x", expand="no")
- def updateProgress(self, value, _max=None, text=""):
- if _max:
- self.max = _max
+ def updateProgress(self, value, max_=None, text=""):
+ if max_:
+ self.max = max_
self.value = value
self.update(None, text)
diff --git a/scripts/config-doc.py b/scripts/config-doc.py
index b193871d2..062badbb1 100755
--- a/scripts/config-doc.py
+++ b/scripts/config-doc.py
@@ -137,10 +137,10 @@ def defaultOptionValue(name, _opt, images):
valueMD = jsonCodeValue(value)
if name.startswith("color.cmd."):
- _hex = termColors[str(value)].lstrip("#")
+ hex_ = termColors[str(value)].lstrip("#")
imageI = f"image{len(images)}"
images.append(
- f".. |{imageI}| image:: https://via.placeholder.com/20/{_hex}/000000?text=+",
+ f".. |{imageI}| image:: https://via.placeholder.com/20/{hex_}/000000?text=+",
)
valueMD += f"\n|{imageI}|"
diff --git a/scripts/wiktextract/extract-schema.py b/scripts/wiktextract/extract-schema.py
index 41cabea4c..644167bc7 100644
--- a/scripts/wiktextract/extract-schema.py
+++ b/scripts/wiktextract/extract-schema.py
@@ -76,14 +76,14 @@ def getSchemaNode(path: list[str]):
return node
-def updateSchema(_type: str, path: list[str]):
+def updateSchema(type_: str, path: list[str]):
node = getSchemaNode(path)
prevType = node.Type
- if prevType and prevType != _type:
+ if prevType and prevType != type_:
print(
- f"mismatch types for path={'.'.join(path)}, {prevType} and {_type}",
+ f"mismatch types for path={'.'.join(path)}, {prevType} and {type_}",
)
- node.Type = _type
+ node.Type = type_
def parseList(data: list[Any], path: list[str], node: Node):
diff --git a/tests/g_appledict_bin_test.py b/tests/g_appledict_bin_test.py
index b795adb48..7c5c82c83 100644
--- a/tests/g_appledict_bin_test.py
+++ b/tests/g_appledict_bin_test.py
@@ -112,9 +112,9 @@ def test_appledict_binary_to_txt_0(self):
"Contents/MyDictionary.xsl",
"Contents/MyDictionary_prefs.html",
]
- _internal = "Images/_internal_dictionary.png"
+ internal = "Images/_internal_dictionary.png"
resFiles = {
- _internal: f"Contents/{_internal}",
+ internal: f"Contents/{internal}",
}
self.convert_appledict_binary_to_txt(baseName, files, resFiles=resFiles)
diff --git a/tests/glossary_test.py b/tests/glossary_test.py
index e32faa85d..475e1dba2 100644
--- a/tests/glossary_test.py
+++ b/tests/glossary_test.py
@@ -99,12 +99,12 @@ def fixDownloadFilename(self, filename):
def downloadFile(self, filename):
unixFilename = filename.replace("\\", "/")
- _crc32 = self.dataFileCRC32[unixFilename]
+ crc32 = self.dataFileCRC32[unixFilename]
fpath = join(testCacheDir, self.fixDownloadFilename(filename))
if isfile(fpath):
with open(fpath, mode="rb") as _file:
data = _file.read()
- if crc32hex(data) != _crc32:
+ if crc32hex(data) != crc32:
raise RuntimeError(f"CRC32 check failed for existing file: {fpath}")
return fpath
try:
@@ -114,7 +114,7 @@ def downloadFile(self, filename):
print(f"{filename=}")
raise e from None
actual_crc32 = crc32hex(data)
- if actual_crc32 != _crc32:
+ if actual_crc32 != crc32:
raise RuntimeError(
"CRC32 check failed for downloaded file: "
f"{filename}: {actual_crc32}",
diff --git a/tests/glossary_v2_test.py b/tests/glossary_v2_test.py
index 61c3c4886..0be34d40c 100644
--- a/tests/glossary_v2_test.py
+++ b/tests/glossary_v2_test.py
@@ -100,12 +100,12 @@ def fixDownloadFilename(self, filename):
def downloadFile(self, filename):
unixFilename = filename.replace("\\", "/")
- _crc32 = self.dataFileCRC32[unixFilename]
+ crc32 = self.dataFileCRC32[unixFilename]
fpath = join(testCacheDir, self.fixDownloadFilename(filename))
if isfile(fpath):
with open(fpath, mode="rb") as _file:
data = _file.read()
- if crc32hex(data) != _crc32:
+ if crc32hex(data) != crc32:
raise RuntimeError(f"CRC32 check failed for existing file: {fpath!r}")
return fpath
try:
@@ -115,7 +115,7 @@ def downloadFile(self, filename):
print(f"{filename=}")
raise e from None
actual_crc32 = crc32hex(data)
- if actual_crc32 != _crc32:
+ if actual_crc32 != crc32:
raise RuntimeError(
"CRC32 check failed for downloaded file: "
f"{filename!r}: {actual_crc32}",
diff --git a/tests/slob_test.py b/tests/slob_test.py
index 74ec4c17a..4f0ba73dc 100644
--- a/tests/slob_test.py
+++ b/tests/slob_test.py
@@ -25,12 +25,12 @@
class StructReaderWriter(slob.StructWriter):
def __init__(
self,
- _file: "io.BufferedWriter",
+ file: "io.BufferedWriter",
reader: "slob.StructReader",
encoding: "str | None" = None,
) -> None:
super().__init__(
- _file=_file,
+ _file=file,
encoding=encoding,
)
self._reader = reader