Skip to content

Commit bf9d60e

Browse files
committed
ruff check
1 parent cd1b45b commit bf9d60e

File tree

8 files changed

+85
-83
lines changed

8 files changed

+85
-83
lines changed

src/dictIO/cli/dict_parser.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,13 +210,13 @@ def _validate_scope(
210210

211211
parser = Parser()
212212
_scope: str = scope.strip(" []")
213-
validated_scope = cast(list[K], [key.strip() for key in _scope.split(",")])
213+
validated_scope = cast("list[K]", [key.strip() for key in _scope.split(",")])
214214
parser.parse_values(validated_scope)
215215
except Exception:
216216
logger.exception(f"setOptions: misspelled scope: {scope}")
217217
else: # string is just a single value.
218218
# Store it not as string but as a (one-element) list
219-
validated_scope = [cast(K, scope)]
219+
validated_scope = [cast("K", scope)]
220220
else: # 'scope' is neither a list nor a string -> set validated_scope to None
221221
validated_scope = None
222222
return validated_scope

src/dictIO/dict.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -90,11 +90,11 @@ def __init__(
9090
base_dict: MutableMapping[K, V] | None = None
9191

9292
if isinstance(arg, Mapping):
93-
base_dict = dict(cast(Mapping[K, V], arg))
93+
base_dict = dict(cast("Mapping[K, V]", arg))
9494
elif isinstance(arg, str | os.PathLike):
9595
source_file = arg
9696
elif isinstance(arg, Iterable):
97-
base_dict = dict(cast(Iterable[tuple[K, V]], arg)) # type: ignore[reportUnnecessaryCast]
97+
base_dict = dict(cast("Iterable[tuple[K, V]]", arg)) # type: ignore[reportUnnecessaryCast]
9898

9999
if base_dict:
100100
super().__init__(base_dict)
@@ -193,9 +193,9 @@ def fromkeys(
193193
SDict[_K, _V] | SDict[_K, Any | None]
194194
The created SDict instance.
195195
"""
196-
new_dict: SDict[_K, _V] = cast(SDict[_K, _V], cls())
196+
new_dict: SDict[_K, _V] = cast("SDict[_K, _V]", cls())
197197
for key in iterable:
198-
new_dict[key] = cast(_V, value) # cast is safe, as `None` is within the type bounds of V
198+
new_dict[key] = cast("_V", value) # cast is safe, as `None` is within the type bounds of V
199199
return new_dict
200200

201201
# TODO @CLAROS: Change return type to `Self` (from `typing`module)
@@ -380,10 +380,10 @@ def extract_variables_from_dict(dict_in: MutableMapping[_K, V]) -> None:
380380
continue
381381
if isinstance(value, MutableSequence):
382382
# special case: item is a list, but does NOT contain a nested dict (-> e.g. a vector or matrix)
383-
variables[key] = cast(V, value)
383+
variables[key] = cast("V", value)
384384
else:
385385
# base case: item is a single value type
386-
value = cast(V, value)
386+
value = cast("V", value)
387387
_value = _insert_expression(value=value, s_dict=self)
388388
if not _value_contains_circular_reference(key, _value):
389389
variables[key] = _value
@@ -542,8 +542,8 @@ def _recursive_merge(
542542
and isinstance(dict_to_merge[key], Mapping)
543543
): # dict
544544
self._recursive_merge( # Recursion
545-
target_dict=cast(MutableMapping[K, V], target_dict[key]),
546-
dict_to_merge=cast(Mapping[K, V], dict_to_merge[key]),
545+
target_dict=cast("MutableMapping[K, V]", target_dict[key]),
546+
dict_to_merge=cast("Mapping[K, V]", dict_to_merge[key]),
547547
overwrite=overwrite,
548548
)
549549
else:
@@ -619,7 +619,7 @@ def include(self, dict_to_include: SDict[_K, _V]) -> None:
619619
continue
620620
break
621621
# cast is safe, as `str` is within the type bounds of both K and V
622-
self[cast(K, placeholder)] = cast(V, placeholder)
622+
self[cast("K", placeholder)] = cast("V", placeholder)
623623
self.includes.update({ii: (include_directive, include_file_name, include_file_path)})
624624
return
625625

@@ -657,18 +657,18 @@ def __or__(
657657
"""
658658
new_dict: SDict[K | _K, V | _V]
659659
new_dict = cast(
660-
SDict[K | _K, V | _V],
660+
"SDict[K | _K, V | _V]",
661661
self.__class__(
662662
cast(
663-
Mapping[K, V],
663+
"Mapping[K, V]",
664664
super().__or__(other),
665665
)
666666
),
667667
)
668668
# update attributes
669669
new_dict._post_update(
670670
cast(
671-
Mapping[K | _K, V | _V],
671+
"Mapping[K | _K, V | _V]",
672672
other,
673673
)
674674
)
@@ -711,11 +711,11 @@ def __ror__(
711711
"""
712712
new_dict: SDict[K | _K, V | _V]
713713
new_dict = cast(
714-
SDict[K | _K, V | _V],
715-
self.__class__(super().__ror__(cast(dict[K, V], other))),
714+
"SDict[K | _K, V | _V]",
715+
self.__class__(super().__ror__(cast("dict[K, V]", other))),
716716
)
717717
# update attributes
718-
new_dict._post_update(cast(SDict[K | _K, V | _V], self))
718+
new_dict._post_update(cast("SDict[K | _K, V | _V]", self))
719719
new_dict._clean()
720720
return new_dict
721721

@@ -1002,7 +1002,7 @@ def _clean_data(self, data: MutableMapping[K, V]) -> None:
10021002
if block_comment in unique_block_comments_on_this_level:
10031003
# Found doublette
10041004
# Remove from current level in data (the dict)
1005-
del data[cast(K, _block_comment)]
1005+
del data[cast("K", _block_comment)]
10061006
# ..AND from self.block_comments (the lookup table)
10071007
del self.block_comments[_id]
10081008
else:
@@ -1016,7 +1016,7 @@ def _clean_data(self, data: MutableMapping[K, V]) -> None:
10161016
if include in unique_includes_on_this_level:
10171017
# Found doublette
10181018
# Remove from current level in data (the dict)
1019-
del data[cast(K, _include)]
1019+
del data[cast("K", _include)]
10201020
# ..AND from self.includes (the lookup table)
10211021
del self.includes[_id]
10221022
else:
@@ -1030,7 +1030,7 @@ def _clean_data(self, data: MutableMapping[K, V]) -> None:
10301030
if line_comment in unique_line_comments_on_this_level:
10311031
# Found doublette
10321032
# Remove from current level in data (the dict)
1033-
del data[cast(K, _line_comment)]
1033+
del data[cast("K", _line_comment)]
10341034
# ..AND from self.line_comments (the lookup table)
10351035
del self.line_comments[_id]
10361036
else:
@@ -1076,12 +1076,12 @@ def _insert_expression(value: V, s_dict: SDict[K, V]) -> V:
10761076
if not isinstance(value, str):
10771077
return value
10781078
if not re.search(r"EXPRESSION\d{6}", value):
1079-
return cast(V, value)
1079+
return cast("V", value)
10801080
if match_index := re.search(r"\d{6}", value):
10811081
index = int(match_index[0])
10821082
_value = s_dict.expressions[index]["expression"] if index in s_dict.expressions else value
1083-
return cast(V, _value)
1084-
return cast(V, value)
1083+
return cast("V", _value)
1084+
return cast("V", value)
10851085

10861086

10871087
def _value_contains_circular_reference(key: TKey, value: TValue) -> bool:

src/dictIO/dict_reader.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ def _merge_includes_recursive(parent_dict: SDict[K, V]) -> SDict[K, V]:
177177
else:
178178
parser = Parser.get_parser(source_file=path)
179179
included_dict = cast(
180-
SDict[K, V],
180+
"SDict[K, V]",
181181
parser.parse_file(
182182
source_file=path,
183183
target_dict=None,
@@ -286,10 +286,10 @@ def _eval_expressions(dict_in: SDict[K, V]) -> None:
286286
eval_result: V | None = None
287287
if "$" not in expression:
288288
try:
289-
eval_result = cast(V, eval(expression)) # noqa: S307
289+
eval_result = cast("V", eval(expression)) # noqa: S307
290290
eval_successful = True
291291
except NameError:
292-
eval_result = cast(V, expression)
292+
eval_result = cast("V", expression)
293293
eval_successful = True
294294
except SyntaxError:
295295
logger.warning(f'DictReader.(): evaluation of "{expression}" not yet possible')
@@ -338,7 +338,7 @@ def _eval_expressions(dict_in: SDict[K, V]) -> None:
338338
expression = item["expression"]
339339
while global_key := dict_in.find_global_key(query=placeholder):
340340
# Substitute the placeholder with the original (or at least partly resolved) expression
341-
dict_in.set_global_key(global_key, value=cast(V, expression))
341+
dict_in.set_global_key(global_key, value=cast("V", expression))
342342
dict_in.expressions.clear()
343343

344344
return
@@ -351,7 +351,7 @@ def _remove_comment_keys(data: M) -> M:
351351
with contextlib.suppress(Exception):
352352
for key in list(data.keys()): # work on a copy of the keys
353353
if isinstance(data[key], MutableMapping):
354-
sub_dict = cast(M, data[key])
354+
sub_dict = cast("M", data[key])
355355
data.update({key: DictReader._remove_comment_keys(sub_dict)}) # recursion
356356
elif re.search(pattern=remove, string=str(key)):
357357
_ = data.pop(key)

src/dictIO/dict_writer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def write(
9494
)
9595
from dictIO import DictReader
9696

97-
existing_dict = cast(SDict[K, V], DictReader.read(source_file=target_file, order=order))
97+
existing_dict = cast("SDict[K, V]", DictReader.read(source_file=target_file, order=order))
9898
existing_dict.merge(source_dict)
9999
source_dict = existing_dict
100100

src/dictIO/formatter.py

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,18 @@
99
from copy import copy, deepcopy
1010
from pathlib import Path
1111
from re import Pattern
12-
from typing import Any, cast, overload
12+
from typing import TYPE_CHECKING, Any, cast, overload
1313
from xml.dom import minidom
1414
from xml.etree.ElementTree import Element, SubElement, register_namespace, tostring
1515

1616
from numpy import ndarray
1717

1818
from dictIO import SDict
19-
from dictIO.types import K, M, S, TKey, TSingleValue, TValue, V
2019
from dictIO.utils.counter import BorgCounter
2120

21+
if TYPE_CHECKING:
22+
from dictIO.types import K, M, S, TKey, TSingleValue, TValue, V
23+
2224
__ALL__ = [
2325
"Formatter",
2426
"NativeFormatter",
@@ -192,9 +194,9 @@ def format_values(
192194
item = _arg[index]
193195
# ndarray -> list
194196
if isinstance(item, ndarray):
195-
item = cast(list[TValue], item.tolist())
197+
item = cast("list[TValue]", item.tolist())
196198
if isinstance(item, MutableMapping | MutableSequence):
197-
_arg[index] = self.format_values(cast(M | S, item))
199+
_arg[index] = self.format_values(cast("M | S", item))
198200
else:
199201
_arg[index] = self.format_value(item)
200202

@@ -203,13 +205,13 @@ def format_values(
203205
item = _arg[key]
204206
# ndarray -> list
205207
if isinstance(item, ndarray):
206-
item = cast(list[TValue], item.tolist())
208+
item = cast("list[TValue]", item.tolist())
207209
if isinstance(item, MutableMapping | MutableSequence):
208-
_arg[key] = self.format_values(cast(M | S, item))
210+
_arg[key] = self.format_values(cast("M | S", item))
209211
else:
210212
_arg[key] = self.format_value(item)
211213

212-
return cast(M | S, _arg)
214+
return cast("M | S", _arg)
213215

214216
def format_key(
215217
self,
@@ -496,10 +498,10 @@ def to_string(
496498
sorted_data: dict[K, V] = {}
497499
for key, element in original_data.items():
498500
if type(key) is str and re.search(r"BLOCKCOMMENT\d{6}", key):
499-
sorted_data[cast(K, key)] = element
501+
sorted_data[cast("K", key)] = element
500502
for key, element in original_data.items():
501503
if type(key) is str and re.search(r"INCLUDE\d{6}", key):
502-
sorted_data[cast(K, key)] = element
504+
sorted_data[cast("K", key)] = element
503505
for key in sorted_data:
504506
del original_data[key]
505507
sorted_data |= original_data
@@ -559,7 +561,7 @@ def format_dict(
559561
item = arg[index]
560562
# ndarray -> list
561563
if isinstance(item, ndarray):
562-
item = cast(list[TValue], item.tolist())
564+
item = cast("list[TValue]", item.tolist())
563565

564566
# nested list
565567
if isinstance(item, MutableSequence):
@@ -632,7 +634,7 @@ def format_dict(
632634
item = arg[key]
633635
# ndarray -> list
634636
if isinstance(item, ndarray):
635-
item = cast(list[TValue], item.tolist())
637+
item = cast("list[TValue]", item.tolist())
636638

637639
# nested dict
638640
if isinstance(item, dict):
@@ -1168,20 +1170,20 @@ def to_string(
11681170
# Check whether xml opts are contained in dict.
11691171
# If so, read and use them
11701172
if "_xmlOpts" in arg:
1171-
xml_opts = cast(MutableMapping[K, V], arg[cast(K, "_xmlOpts")])
1173+
xml_opts = cast("MutableMapping[K, V]", arg[cast("K", "_xmlOpts")])
11721174
namespaces = (
1173-
cast(MutableMapping[str, str], xml_opts[cast(K, "_nameSpaces")])
1175+
cast("MutableMapping[str, str]", xml_opts[cast("K", "_nameSpaces")])
11741176
if "_nameSpaces" in xml_opts
11751177
else namespaces
11761178
)
1177-
root_tag = str(xml_opts[cast(K, "_rootTag")]) if "_rootTag" in xml_opts else root_tag
1179+
root_tag = str(xml_opts[cast("K", "_rootTag")]) if "_rootTag" in xml_opts else root_tag
11781180
root_attributes = (
1179-
cast(MutableMapping[str, str], xml_opts[cast(K, "_rootAttributes")])
1181+
cast("MutableMapping[str, str]", xml_opts[cast("K", "_rootAttributes")])
11801182
if "_rootAttributes" in xml_opts
11811183
else root_attributes
11821184
)
11831185
self.remove_node_numbering = (
1184-
bool(xml_opts[cast(K, "_removeNodeNumbering")])
1186+
bool(xml_opts[cast("K", "_removeNodeNumbering")])
11851187
if "_removeNodeNumbering" in xml_opts
11861188
else self.remove_node_numbering
11871189
)

0 commit comments

Comments
 (0)