Skip to content

Commit 8df9330

Browse files
authored
Linting updates from changeover to ruff from pylint (#69)
1 parent ec5f510 commit 8df9330

22 files changed

Lines changed: 130 additions & 139 deletions

‎pyproject.toml‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,14 @@ filterwarnings = "ignore::DeprecationWarning"
7171

7272
[tool.ruff]
7373
line-length = 120
74+
exclude = [
75+
"tests/od/**",
76+
]
77+
78+
[tool.ruff.lint.per-file-ignores]
79+
"tests/*" = [
80+
"S101", # Allow use of assert statements in tests
81+
]
82+
"tests/test_imports.py" = [
83+
"F401", # Allow unused imports in this file
84+
]

‎src/objdictgen/__main__.py‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def inner(*args, **kw):
6363
opts = DebugOpts()
6464
try:
6565
return fn(opts, *args, **kw)
66-
except Exception as exc: # pylint: disable=broad-except
66+
except Exception as exc:
6767
if opts.show_debug:
6868
raise
6969
print(f"{ODG_PROGRAM}: {exc.__class__.__name__}: {exc}")
@@ -212,8 +212,8 @@ def main(debugopts: DebugOpts, args: Sequence[str]|None = None):
212212
if opts.command == "help":
213213
if opts.subcommand:
214214
for subparsers_action in (
215-
a for a in parser._actions # pylint: disable=protected-access
216-
if isinstance(a, argparse._SubParsersAction) # pylint: disable=protected-access
215+
a for a in parser._actions
216+
if isinstance(a, argparse._SubParsersAction)
217217
):
218218
for choice, subparser in subparsers_action.choices.items():
219219
if choice != opts.subcommand:
@@ -294,8 +294,7 @@ def main(debugopts: DebugOpts, args: Sequence[str]|None = None):
294294
elif opts.command == "edit":
295295

296296
# Import here to prevent including optional UI components for cmd-line use
297-
from .ui.objdictedit import \
298-
uimain # pylint: disable=import-outside-toplevel
297+
from .ui.objdictedit import uimain
299298
uimain(opts.od)
300299

301300

@@ -322,17 +321,15 @@ def main(debugopts: DebugOpts, args: Sequence[str]|None = None):
322321
elif opts.command == "network":
323322

324323
# Import here to prevent including optional UI components for cmd-line use
325-
from .ui.networkedit import \
326-
uimain # pylint: disable=import-outside-toplevel
324+
from .ui.networkedit import uimain
327325
uimain(opts.dir)
328326

329327

330328
# -- NODELIST command --
331329
elif opts.command == "nodelist":
332330

333331
# Import here to prevent including optional UI components for cmd-line use
334-
from .nodelist import \
335-
main as _main # pylint: disable=import-outside-toplevel
332+
from .nodelist import main as _main
336333
_main(opts.dir)
337334

338335

@@ -342,5 +339,4 @@ def main(debugopts: DebugOpts, args: Sequence[str]|None = None):
342339

343340
# To support -m objdictgen
344341
if __name__ == '__main__':
345-
# pylint: disable=no-value-for-parameter
346342
main()

‎src/objdictgen/eds_utils.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,9 @@
6060
}
6161

6262
# Function for verifying data values
63-
is_integer = lambda x: isinstance(x, int) # pylint: disable=unnecessary-lambda-assignment
64-
is_string = lambda x: isinstance(x, str) # pylint: disable=unnecessary-lambda-assignment
65-
is_boolean = lambda x: x in (0, 1) # pylint: disable=unnecessary-lambda-assignment
63+
is_integer = lambda x: isinstance(x, int) # noqa: E731
64+
is_string = lambda x: isinstance(x, str) # noqa: E731
65+
is_boolean = lambda x: x in (0, 1) # noqa: E731
6666

6767
# Define checking of value for each attribute
6868
ENTRY_ATTRIBUTES: dict[str, Callable[[Any], bool]] = {
@@ -505,7 +505,6 @@ def generate_eds_content(node: Node, filepath: TPath):
505505
entries = list(node)
506506

507507
# FIXME: Too many camelCase vars in here
508-
# pylint: disable=invalid-name
509508

510509
try:
511510
value = node.GetEntry(0x1018)

‎src/objdictgen/gen_cfile.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def text(self, s: str = "") -> Text:
114114
# FIXME: Delete this method when everything is converted to f-strings
115115
def ftext(self, s: str) -> Text:
116116
"""Format a text string."""
117-
return Text(self, "").__imod__(s) # pylint: disable=unnecessary-dunder-call
117+
return Text(self, "").__imod__(s)
118118

119119
def get_valid_type_infos(self, typename: str, items=None) -> TypeInfos:
120120
"""Get valid type infos from a typename.
@@ -191,7 +191,6 @@ def generate_file_content(node: NodeProtocol, headerfile: str, pointers_dict=Non
191191
"""
192192

193193
# FIXME: Too many camelCase vars in here
194-
# pylint: disable=invalid-name
195194

196195
# Setup the main context to store the data
197196
ctx = CFileContext()

‎src/objdictgen/jsonod.py‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,25 @@
3131
import jsonschema
3232

3333
import objdictgen
34+
3435
# Accessed by node.py, so we need to import node as module to avoid circular references
3536
from objdictgen import maps
3637
from objdictgen import node as nodelib
3738
from objdictgen.maps import OD, ODMapping, ODMappingList
38-
from objdictgen.typing import (TDiffNodes, TIndexEntry, TODJson, TODObj,
39-
TODObjJson, TODSubObj, TODSubObjJson, TODValue,
40-
TParamEntry, TPath, TProfileMenu)
41-
from objdictgen.utils import (copy_in_order, exc_amend, maybe_number,
42-
str_to_int, strip_brackets)
39+
from objdictgen.typing import (
40+
TDiffNodes,
41+
TIndexEntry,
42+
TODJson,
43+
TODObj,
44+
TODObjJson,
45+
TODSubObj,
46+
TODSubObjJson,
47+
TODValue,
48+
TParamEntry,
49+
TPath,
50+
TProfileMenu,
51+
)
52+
from objdictgen.utils import copy_in_order, exc_amend, maybe_number, str_to_int, strip_brackets
4353

4454
T = TypeVar('T')
4555
M = TypeVar('M', bound=Mapping)
@@ -352,10 +362,10 @@ def generate_jsonc(node: Node, compact=False, sort=False, internal=False,
352362

353363
if jsonc:
354364
# In jsonc the field is converted to "<field>, // <comment>"
355-
repl = lambda m: m[1].replace('\\"', '"') + m[3] + m[2]
365+
repl = lambda m: m[1].replace('\\"', '"') + m[3] + m[2] # noqa: E731
356366
else:
357367
# In json the field is converted to "<field>,"
358-
repl = lambda m: m[1].replace('\\"', '"') + m[3]
368+
repl = lambda m: m[1].replace('\\"', '"') + m[3] # noqa: E731
359369

360370
# Convert the special @@ fields to jsonc comments
361371
# Syntax: "@@<field>, // <comment>@@"
@@ -396,7 +406,7 @@ def generate_node(contents: str|TODJson, validate: bool = True) -> Node:
396406
# validate_fromdict() is better at giving useful errors
397407
# than the json validator. However the type checking of the json
398408
# validator is better.
399-
global SCHEMA # pylint: disable=global-statement
409+
global SCHEMA
400410
if not SCHEMA:
401411
with open(objdictgen.JSON_SCHEMA, 'r', encoding="utf-8") as f:
402412
SCHEMA = json.loads(remove_jsonc(f.read()))

‎src/objdictgen/maps.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@
3030
from typing import TYPE_CHECKING, Any, Callable, Generator, TypeVar
3131

3232
import objdictgen
33-
from objdictgen.typing import (TODObj, TODSubObj, TODValue, TParamEntry, TPath,
34-
TProfileMenu)
33+
from objdictgen.typing import TODObj, TODSubObj, TODValue, TParamEntry, TPath, TProfileMenu
3534

3635
T = TypeVar('T')
3736

@@ -327,15 +326,14 @@ def import_profile(profilename: TPath) -> tuple["ODMapping", TProfileMenu]:
327326

328327
# Mapping and AddMenuEntries are expected to be defined by the execfile
329328
# The profiles requires some vars to be set
330-
# pylint: disable=unused-variable
331329
try:
332330
with open(profilepath, "r", encoding="utf-8") as f:
333331
log.debug("EXECFILE %s", profilepath)
334332
code = compile(f.read(), profilepath, 'exec')
335333
exec(code, globals(), locals()) # FIXME: Using exec is unsafe
336-
# pylint: disable=undefined-variable
337-
return Mapping, AddMenuEntries # type: ignore[name-defined] # due to the exec() magic
338-
except Exception as exc: # pylint: disable=broad-except
334+
# NOTE: These seem missing due to the exec() magic
335+
return Mapping, AddMenuEntries # type: ignore[name-defined] # noqa: F821
336+
except Exception as exc:
339337
log.debug("EXECFILE FAILED: %s", exc)
340338
log.debug(traceback.format_exc())
341339
raise ValueError(f"Loading profile '{profilepath}' failed: {exc}") from exc

‎src/objdictgen/nodelist.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def SaveMasterNode(self, netname: str = ""):
151151
masterpath = self.Root / "master.od"
152152
try:
153153
self.Manager.SaveCurrentInFile(masterpath)
154-
except Exception as exc: # pylint: disable=broad-except
154+
except Exception as exc:
155155
raise ValueError(f"Fail to save master node in '{masterpath}'") from exc
156156

157157
def LoadSlaveNodes(self, netname: str = ""):
@@ -174,7 +174,7 @@ def LoadSlaveNodes(self, netname: str = ""):
174174
self.LoadEDS(node["DCFName"])
175175
self.AddSlaveNode(node["Name"], nodeid, node["DCFName"])
176176
self.Changed = False
177-
except Exception as exc: # pylint: disable=broad-except
177+
except Exception as exc:
178178
raise ValueError(f"Unable to load CPJ file '{cpjpath}'") from exc
179179

180180
def SaveNodeList(self, netname: str = ""):
@@ -188,7 +188,7 @@ def SaveNodeList(self, netname: str = ""):
188188
with open(cpjpath, mode=mode, encoding="utf-8") as f:
189189
f.write(content)
190190
self.Changed = False
191-
except Exception as exc: # pylint: disable=broad-except
191+
except Exception as exc:
192192
raise ValueError(f"Fail to save node list in '{cpjpath}'") from exc
193193

194194
def GetOrderNumber(self, nodeid: int) -> int:

‎src/objdictgen/nodemanager.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444

4545
# Returns a new id
4646
def get_new_id():
47-
global CURRENTID # pylint: disable=global-statement
47+
global CURRENTID
4848
CURRENTID += 1
4949
return CURRENTID
5050

‎src/objdictgen/nosis.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ def xmldump(filehandle: io.TextIOWrapper|None, py_obj: object,
255255
omit = omit or ()
256256

257257
# Store the ref id to the pickling object (if not deepcopying)
258-
global VISITED # pylint: disable=global-statement
258+
global VISITED
259259
objid = id(py_obj)
260260
VISITED = {
261261
objid: py_obj
@@ -316,7 +316,7 @@ def xmlload(filehandle: SupportsRead[str|bytes]|bytes|str) -> Any:
316316
elif isinstance(filehandle, bytes):
317317
fh = io.BytesIO(filehandle)
318318

319-
global VISITED # pylint: disable=global-statement
319+
global VISITED
320320
VISITED = {} # Reset the visited collection
321321

322322
return _thing_from_dom(minidom.parse(fh), None)
@@ -511,7 +511,7 @@ def _thing_from_dom(dom_node: minidom.Element|minidom.Document, container: Any =
511511
# a value= attribute. ie. pickler can place it in either
512512
# place (based on user preference) and unpickler doesn't care
513513
node_valuetext = ""
514-
if 'value' in node._attrs: # type: ignore[attr-defined] # pylint: disable=protected-access
514+
if 'value' in node._attrs:
515515
# text in tag
516516
ttext = node.getAttribute('value')
517517
node_valuetext = unsafe_string(ttext, isattr=True)
@@ -557,7 +557,6 @@ def _thing_from_dom(dom_node: minidom.Element|minidom.Document, container: Any =
557557
# clearer to show all cases being handled (easier to see the pattern
558558
# when doing later maintenance).
559559

560-
# pylint: disable=self-assigning-variable
561560
if node_type == 'None':
562561
node_val = None
563562
elif node_type == 'numeric':

‎src/objdictgen/typing.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,6 @@
9292
class NodeProtocol(Protocol):
9393
"""Protocol for the Node class."""
9494

95-
# pylint: disable=unnecessary-ellipsis
96-
9795
Name: str
9896
"""Name of the node."""
9997

0 commit comments

Comments
 (0)