Skip to content

Commit

Permalink
fix pylint ruff errors with ruff 0.3.2 and --preview mode
Browse files Browse the repository at this point in the history
  • Loading branch information
ilius committed Mar 13, 2024
1 parent 120ddbb commit f74235e
Show file tree
Hide file tree
Showing 80 changed files with 468 additions and 397 deletions.
2 changes: 1 addition & 1 deletion doc/lib-examples/oxford.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,6 @@ def takePhonetic_oxford_gb(glos):
# .replace("/", "")
# .replace("\\n ", "\\n")
# .replace("\\n ", "\\n")
if ph != "":
if ph:
phonGlos.addEntryObj(phonGlos.newEntry(word, ph))
return phonGlos
9 changes: 6 additions & 3 deletions pyglossary/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def emit(self, record: logging.LogRecord) -> None:
###
levelname = record.levelname

fp = sys.stderr if levelname in ("CRITICAL", "ERROR") else sys.stdout
fp = sys.stderr if levelname in {"CRITICAL", "ERROR"} else sys.stdout

if not self.noColor and levelname in self.colorsConfig:
key, default = self.colorsConfig[levelname]
Expand Down Expand Up @@ -269,7 +269,10 @@ def checkCreateConfDir() -> None:
except Exception as e:
log.warning(f"failed to create user plugins directory: {e}")
if not isfile(confJsonFile):
with open(rootConfJsonFile) as srcF, open(confJsonFile, "w") as usrF:
with (
open(rootConfJsonFile, encoding="utf-8") as srcF,
open(confJsonFile, "w", encoding="utf-8") as usrF,
):
usrF.write(srcF.read())


Expand Down Expand Up @@ -385,7 +388,7 @@ def _unix_show_exception(
# can set env var WARNINGS to:
# "error", "ignore", "always", "default", "module", "once"
if WARNINGS := os.getenv("WARNINGS"):
if WARNINGS in ("default", "error", "ignore", "always", "module", "once"):
if WARNINGS in {"default", "error", "ignore", "always", "module", "once"}:
import warnings

warnings.filterwarnings(WARNINGS) # type: ignore # noqa: PGH003
Expand Down
16 changes: 9 additions & 7 deletions pyglossary/entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ class DataEntry(BaseEntry):
"_tmpPath",
]

def isData(self) -> bool:
@classmethod
def isData(cls) -> bool:
return True

def __init__(
Expand Down Expand Up @@ -185,7 +186,8 @@ class Entry(BaseEntry):
"_word",
]

def isData(self) -> bool:
@classmethod
def isData(cls) -> bool:
return False

@staticmethod
Expand Down Expand Up @@ -234,7 +236,7 @@ def __init__(
elif not isinstance(defi, str):
raise TypeError(f"invalid defi type {type(defi)}")

if defiFormat not in ("m", "h", "x"):
if defiFormat not in {"m", "h", "x"}:
raise ValueError(f"invalid defiFormat {defiFormat!r}")

self._word = word
Expand Down Expand Up @@ -332,7 +334,8 @@ def editFuncDefi(self, func: "Callable[[str], str]") -> None:
"""
self._defi = func(self._defi)

def _stripTrailingBR(self, s: str) -> str:
@classmethod
def _stripTrailingBR(cls, s: str) -> str:
while s.endswith(("<BR>", "<br>")):
s = s[:-4]
return s
Expand Down Expand Up @@ -377,9 +380,8 @@ def stripFullHtml(self) -> "str | None":
defi = defi[len("<!DOCTYPE html>") :].strip()
if not defi.startswith("<html"):
return "Has <!DOCTYPE html> but no <html>"
else:
if not defi.startswith("<html>"):
return None
elif not defi.startswith("<html>"):
return None
i = defi.find("<body")
if i == -1:
return "<body not found"
Expand Down
26 changes: 14 additions & 12 deletions pyglossary/entry_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def __init__(self, glos: "GlossaryType") -> None:
def prepare(self) -> None:
"""Run this after glossary info is set and ready."""

def run(self, entry: "EntryType") -> "EntryType | None":
def run(self, entry: "EntryType") -> "EntryType | None": # noqa: PLR6301
"""
Return an Entry object, or None to skip.
Expand All @@ -69,7 +69,7 @@ class TrimWhitespaces(EntryFilter):
name = "trim_whitespaces"
desc = "Remove leading/trailing whitespaces from word(s) and definition"

def run(self, entry: "EntryType") -> "EntryType | None":
def run(self, entry: "EntryType") -> "EntryType | None": # noqa: PLR6301
entry.strip()
entry.replace("\r", "")
return entry
Expand All @@ -79,7 +79,7 @@ class NonEmptyWordFilter(EntryFilter):
name = "non_empty_word"
desc = "Skip entries with empty word"

def run(self, entry: "EntryType") -> "EntryType | None":
def run(self, entry: "EntryType") -> "EntryType | None": # noqa: PLR6301
if not entry.s_word:
return None
return entry
Expand All @@ -89,7 +89,7 @@ class NonEmptyDefiFilter(EntryFilter):
name = "non_empty_defi"
desc = "Skip entries with empty definition"

def run(self, entry: "EntryType") -> "EntryType | None":
def run(self, entry: "EntryType") -> "EntryType | None": # noqa: PLR6301
if not entry.defi:
return None
return entry
Expand All @@ -99,7 +99,7 @@ class RemoveEmptyAndDuplicateAltWords(EntryFilter):
name = "remove_empty_dup_alt_words"
desc = "Remove empty and duplicate alternate words"

def run(self, entry: "EntryType") -> "EntryType | None":
def run(self, entry: "EntryType") -> "EntryType | None": # noqa: PLR6301
entry.removeEmptyAndDuplicateAltWords()
if not entry.l_word:
return None
Expand All @@ -111,7 +111,7 @@ class FixUnicode(EntryFilter):
desc = "Fix Unicode in word(s) and definition"
falseComment = "Do not fix Unicode in word(s) and definition"

def run(self, entry: "EntryType") -> "EntryType | None":
def run(self, entry: "EntryType") -> "EntryType | None": # noqa: PLR6301
entry.editFuncWord(fixUtf8)
entry.editFuncDefi(fixUtf8)
return entry
Expand Down Expand Up @@ -142,7 +142,7 @@ class RTLDefi(EntryFilter):
name = "rtl"
desc = "Make definition right-to-left"

def run(self, entry: "EntryType") -> "EntryType | None":
def run(self, entry: "EntryType") -> "EntryType | None": # noqa: PLR6301
entry.editFuncDefi(lambda defi: f'<div dir="rtl">{defi}</div>')
return entry

Expand Down Expand Up @@ -271,7 +271,8 @@ def __init__(
re.DOTALL | re.IGNORECASE,
)

def _subLower(self, m: "re.Match") -> str:
@staticmethod
def _subLower(m: "re.Match") -> str:
return m.group(0).lower()

def _fixDefi(self, st: str) -> str:
Expand All @@ -286,7 +287,7 @@ class SkipDataEntry(EntryFilter):
name = "skip_resources"
desc = "Skip resources / data files"

def run(self, entry: "EntryType") -> "EntryType | None":
def run(self, entry: "EntryType") -> "EntryType | None": # noqa: PLR6301
if entry.isData():
return None
return entry
Expand All @@ -310,7 +311,7 @@ def prepare(self) -> None:
self._run_func = self.run_fa
log.info("Using Persian filter")

def run_fa(self, entry: "EntryType") -> "EntryType | None":
def run_fa(self, entry: "EntryType") -> "EntryType | None": # noqa: PLR6301
from .persian_utils import faEditStr

entry.editFuncWord(faEditStr)
Expand Down Expand Up @@ -492,6 +493,7 @@ def run(self, entry: "EntryType") -> "EntryType | None":
class ShowMaxMemoryUsage(EntryFilter):
name = "max_memory_usage"
desc = "Show Max Memory Usage"
MAX_WORD_LEN = 30

def __init__(self, glos: "GlossaryType") -> None:
import os
Expand All @@ -507,8 +509,8 @@ def run(self, entry: "EntryType") -> "EntryType | None":
if usage > self._max_mem_usage:
self._max_mem_usage = usage
word = entry.s_word
if len(word) > 30:
word = word[:37] + "..."
if len(word) > self.MAX_WORD_LEN:
word = word[:self.MAX_WORD_LEN - 3] + "..."
core.trace(log, f"MaxMemUsage: {usage:,}, {word=}")
return entry

Expand Down
3 changes: 2 additions & 1 deletion pyglossary/glossary.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ def read(
def addEntryObj(self, entry: "EntryType") -> None:
self._data.append(entry)

def updateIter(self) -> None:
@staticmethod
def updateIter() -> None:
log.warning("calling glos.updateIter() is no longer needed.")

def sortWords(
Expand Down
9 changes: 5 additions & 4 deletions pyglossary/glossary_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ def author(self) -> str:
return value
return ""

def _getLangByStr(self, st: str) -> "Lang | None":
@staticmethod
def _getLangByStr(st: str) -> "Lang | None":
lang = langDict[st]
if lang:
return lang
Expand Down Expand Up @@ -209,13 +210,13 @@ def checkPart(part: str) -> None:
for part in re.split("-| to ", name):
# print(f"{part = }")
checkPart(part)
if len(langNames) >= 2:
if len(langNames) >= 2: # noqa: PLR2004
break

if len(langNames) < 2:
if len(langNames) < 2: # noqa: PLR2004
return

if len(langNames) > 2:
if len(langNames) > 2: # noqa: PLR2004
log.info(f"detectLangsFromName: {langNames = }")

log.info(
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/glossary_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def progressbar(self, enabled: bool) -> None:

def progressInit(
self,
*args, # noqa: ANN
*args, # noqa: ANN003
) -> None:
if self._ui and self._progressbar:
self._ui.progressInit(*args)
Expand Down
6 changes: 4 additions & 2 deletions pyglossary/glossary_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@

log = logging.getLogger("pyglossary")

MAX_EXT_LEN = 4 # FIXME


def splitFilenameExt(
filename: str = "",
Expand All @@ -40,13 +42,13 @@ def splitFilenameExt(
filenameNoExt, ext = splitext(filename)
ext = ext.lower()

if not ext and len(filenameNoExt) < 5:
if not ext and len(filenameNoExt) <= MAX_EXT_LEN:
filenameNoExt, ext = "", filenameNoExt

if not ext:
return filename, filename, "", ""

if ext[1:] in (*stdCompressions, "zip", "dz"):
if ext[1:] in {*stdCompressions, "zip", "dz"}:
compression = ext[1:]
filename = filenameNoExt
filenameNoExt, ext = splitext(filename)
Expand Down
18 changes: 8 additions & 10 deletions pyglossary/glossary_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ def _entryFromRaw(self, rawEntryArg: "RawEntryType") -> "EntryType":
rawEntry = rawEntryArg
word = rawEntry[0]
defi = rawEntry[1].decode("utf-8")
if len(rawEntry) > 2:
if len(rawEntry) > 2: # noqa: PLR2004
defiFormat = rawEntry[2]
if defiFormat == "b":
fname = word
Expand Down Expand Up @@ -408,7 +408,7 @@ def _applyEntryFiltersGen(
if entry is None:
continue
for entryFilter in self._entryFilters:
entry = entryFilter.run(entry)
entry = entryFilter.run(entry) # noqa: PLW2901
if entry is None:
break
else:
Expand Down Expand Up @@ -655,7 +655,7 @@ def _openReader(self, reader: "Any", filename: str) -> bool:
self.progressInit("Reading metadata")
lastPos = -100_000
for pos, total in openResult:
if progressbar and pos - lastPos > 100_000:
if progressbar and pos - lastPos > 100_000: # noqa: PLR2004
self.progress(pos, total, unit="bytes")
lastPos = pos
self.progressEnd()
Expand Down Expand Up @@ -850,8 +850,8 @@ def _writeEntries(
with suppress(StopIteration):
gen.send(None)

@staticmethod
def _openWriter(
self,
writer: "Any",
filename: str,
) -> bool:
Expand Down Expand Up @@ -967,8 +967,8 @@ def _switchToSQLite(
self._config["enable_alts"] = True
self._sqlite = True

@staticmethod
def _checkSortFlag(
self,
plugin: "PluginProp",
sort: "bool | None",
) -> "bool | None":
Expand Down Expand Up @@ -1051,8 +1051,8 @@ def _resolveSortParams(

return False, True

@staticmethod
def _checkSortKey(
self,
plugin: "PluginProp",
sortKeyName: "str | None",
sortEncoding: "str | None",
Expand Down Expand Up @@ -1092,10 +1092,8 @@ def _checkSortKey(

return namedSortKey, sortEncoding

def _convertValidateStrings(
self,
args: ConvertArgs,
) -> None:
@staticmethod
def _convertValidateStrings(args: ConvertArgs) -> None:
if type(args.inputFilename) is not str:
raise TypeError("inputFilename must be str")
if type(args.outputFilename) is not str:
Expand Down
8 changes: 4 additions & 4 deletions pyglossary/gregorian.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ def isLeap(y: int) -> bool:


def to_jd(year: int, month: int, day: int) -> int:
if 0 < year < 10000: # > 1.5x faster
if 0 < year < 10000: # > 1.5x faster # noqa: PLR2004
return datetime(year, month, day).toordinal() + 1721425

if month <= 2:
if month <= 2: # noqa: PLR2004
tm = 0
elif isLeap(year):
tm = -1
Expand All @@ -67,7 +67,7 @@ def to_jd(year: int, month: int, day: int) -> int:

def jd_to(jd: int) -> "tuple[int, int, int]":
ordinal = jd - 1721425
if 0 < ordinal < 3652060: # > 4x faster
if 0 < ordinal < 3652060: # > 4x faster # noqa: PLR2004
# datetime(9999, 12, 31).toordinal() == 3652059
dt = datetime.fromordinal(ordinal)
return (dt.year, dt.month, dt.day)
Expand All @@ -82,7 +82,7 @@ def jd_to(jd: int) -> "tuple[int, int, int]":
cent * 100 +
quad * 4 +
yindex +
(cent != 4 and yindex != 4)
(cent != 4 and yindex != 4) # noqa: PLR2004
)
yearday = jd - to_jd(year, 1, 1)

Expand Down
6 changes: 3 additions & 3 deletions pyglossary/html_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@
"Egrave": 0x00C8, # È
"egrave": 0x00E8, # è
"empty": 0x2205, # ∅
"emsp": 0x2003, #
"ensp": 0x2002, #
"emsp": 0x2003,
"ensp": 0x2002,
"Epsilon": 0x0395, # Ε
"epsilon": 0x03B5, # ε
"equiv": 0x2261, # ≡
Expand Down Expand Up @@ -267,7 +267,7 @@
"Theta": 0x0398, # Θ
"theta": 0x03B8, # θ
"thetasym": 0x03D1, # ϑ
"thinsp": 0x2009, #
"thinsp": 0x2009,
"THORN": 0x00DE, # Þ
"thorn": 0x00FE, # þ
"tilde": 0x02DC, # ˜
Expand Down
2 changes: 1 addition & 1 deletion pyglossary/lxml_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
TypeAlias,
)

from lxml.etree import QName, _Element
from lxml.etree import QName, _Element # noqa: PLC2701

__all__ = ["Element", "T_htmlfile"]

Expand Down
Loading

0 comments on commit f74235e

Please sign in to comment.