Skip to content

Commit ac48a07

Browse files
authored
Minor list index improvements
1 parent 6e7ae79 commit ac48a07

File tree

2 files changed

+11
-14
lines changed

2 files changed

+11
-14
lines changed

dpath/segments.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from dpath import options
66
from dpath.exceptions import InvalidGlob, InvalidKeyName, PathNotFound
7-
from dpath.types import PathSegment, Creator, Hints, Glob, Path, SymmetricInt
7+
from dpath.types import PathSegment, Creator, Hints, Glob, Path, ListIndex
88

99

1010
def make_walkable(node) -> Iterator[Tuple[PathSegment, Any]]:
@@ -22,8 +22,8 @@ def make_walkable(node) -> Iterator[Tuple[PathSegment, Any]]:
2222
except AttributeError:
2323
try:
2424
indices = range(len(node))
25-
# Convert all list indices to object so negative indexes are supported.
26-
indices = map(lambda i: SymmetricInt(i, len(node)), indices)
25+
# Convert all list indices to objects so negative indices are supported.
26+
indices = map(lambda i: ListIndex(i, len(node)), indices)
2727
return zip(indices, node)
2828
except TypeError:
2929
# This can happen in cases where the node isn't leaf(node) == True,

dpath/types.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,29 @@
22
from typing import Union, Any, Callable, Sequence, Tuple, List, Optional, MutableMapping
33

44

5-
class SymmetricInt(int):
6-
"""Same as a normal int but mimicks the behavior of list indexes (can be compared to a negative number)."""
5+
class ListIndex(int):
6+
"""Same as a normal int but mimics the behavior of list indices (can be compared to a negative number)."""
77

8-
def __new__(cls, value: int, max_value: int, *args, **kwargs):
9-
if value >= max_value:
8+
def __new__(cls, value: int, list_length: int, *args, **kwargs):
9+
if value >= list_length:
1010
raise TypeError(
1111
f"Tried to initiate a {cls.__name__} with a value ({value}) "
12-
f"greater than the provided max value ({max_value})"
12+
f"greater than the provided max value ({list_length})"
1313
)
1414

1515
obj = super().__new__(cls, value)
16-
obj.max_value = max_value
16+
obj.list_length = list_length
1717

1818
return obj
1919

2020
def __eq__(self, other):
2121
if not isinstance(other, int):
2222
return False
2323

24-
if other >= self.max_value or other <= -self.max_value:
25-
return False
26-
27-
return int(self) == (self.max_value + other) % self.max_value
24+
return other == int(self) or self.list_length + other == int(self)
2825

2926
def __repr__(self):
30-
return f"<{self.__class__.__name__} {int(self)}%{self.max_value}>"
27+
return f"<{self.__class__.__name__} {int(self)}/{self.list_length}>"
3128

3229
def __str__(self):
3330
return str(int(self))

0 commit comments

Comments
 (0)