Skip to content

Commit

Permalink
fix ruff 0.8.2 preview errors
Browse files Browse the repository at this point in the history
  • Loading branch information
ilius committed Dec 5, 2024
1 parent 5419402 commit 83a1a2b
Show file tree
Hide file tree
Showing 41 changed files with 330 additions and 327 deletions.
6 changes: 3 additions & 3 deletions pyglossary/compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
30 changes: 15 additions & 15 deletions pyglossary/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
4 changes: 2 additions & 2 deletions pyglossary/ebook_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,15 +223,15 @@ 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:
self.add_file(relative_path, contents)
self.manifest_files.append(
{
"path": relative_path,
"id": _id,
"id": id_,
"mimetype": mimetype,
},
)
Expand Down
6 changes: 3 additions & 3 deletions pyglossary/glossary_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ def wordTitleStr(
self,
word: str,
sample: str = "",
_class: str = "",
class_: str = "",
) -> str:
"""
Return title tag for words.
Expand All @@ -573,8 +573,8 @@ def wordTitleStr(
if not sample:
sample = word
tag = self.titleTag(sample)
if _class:
return f'<{tag} class="{_class}">{word}</{tag}><br>'
if class_:
return f'<{tag} class="{class_}">{word}</{tag}><br>'
return f"<{tag}>{word}</{tag}><br>"

def getConfig(self, name: str, default: str | None) -> str | None:
Expand Down
22 changes: 11 additions & 11 deletions pyglossary/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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,
)
Expand All @@ -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,
),
Expand Down
10 changes: 5 additions & 5 deletions pyglossary/plugin_prop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand All @@ -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:
Expand Down Expand Up @@ -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}"
Expand Down
22 changes: 11 additions & 11 deletions pyglossary/plugins/aard2_slob.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -412,33 +412,33 @@ def addEntry(self, entry: EntryType) -> None:
b_defi = b_defi.replace(b"""<img src="file:///""", b'''<img src="''')
b_defi = b_defi.replace(b"""<img src='file:///""", b"""<img src='""")

if not _ctype:
if not ctype:
if defiFormat == "h":
_ctype = "text/html; charset=utf-8"
ctype = "text/html; charset=utf-8"
elif defiFormat == "m":
_ctype = "text/plain; charset=utf-8"
ctype = "text/plain; charset=utf-8"
else:
_ctype = "text/plain; charset=utf-8"
ctype = "text/plain; charset=utf-8"

if not self._separate_alternates:
writer.add(
b_defi,
*tuple(words),
content_type=_ctype,
content_type=ctype,
)
return

headword, *alts = words
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]:
Expand Down
18 changes: 9 additions & 9 deletions pyglossary/plugins/appledict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`",
)

Expand Down Expand Up @@ -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
Expand All @@ -335,7 +335,7 @@ def write(self) -> Generator[None, EntryType, None]: # noqa: PLR0912
content = prepare_content(content_title, defi, BeautifulSoup)

toFile.write(
f'<d:entry id="{_id}" d:title={quoted_title}>\n'
f'<d:entry id="{id_}" d:title={quoted_title}>\n'
+ generate_indexes(long_title, alts, content, BeautifulSoup)
+ content
+ "\n</d:entry>\n",
Expand All @@ -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,
)
Expand Down Expand Up @@ -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),
Expand Down
14 changes: 7 additions & 7 deletions pyglossary/plugins/appledict_bin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)}")
Expand All @@ -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)
Expand Down
Loading

0 comments on commit 83a1a2b

Please sign in to comment.