Skip to content

Commit

Permalink
add __invert__() (__invert__ = __reversed__) and change __neg__
Browse files Browse the repository at this point in the history
  • Loading branch information
bleudev committed May 28, 2024
1 parent ceead0b commit 5b2db39
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
3 changes: 2 additions & 1 deletion tests/test_udict.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def test_reverse(self):

self.assertDictEqual(d2, ud.reversed().dictionary)
self.assertEqual(reversed(ud), ud.reversed())
self.assertEqual(-ud, ud.reverse())
self.assertEqual(~ud, ud.reverse())

def test_sort(self):
d = {'hi': 2, 'hello': 1}
Expand Down Expand Up @@ -87,6 +87,7 @@ def test_get(self):
# TODO: test_str_and_repr
# TODO: test_cmp_and_eq
# TODO: test_math_operations
# TODO: test_neg


if __name__ == '__main__':
Expand Down
8 changes: 6 additions & 2 deletions ufpy/udict.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ def __call__(self, func: Callable[[KT, VT], VT]) -> 'UDict[KT, VT, DV]':
for k, v in self:
new_dict[k] = func(k, v)
return UDict(new_dict, default=self.__default)

# reverse integers
def __neg__(self) -> 'UDict[KT, VT, DV]':
return self(lambda k, v: -v)

# reverse
def reverse(self) -> 'UDict[KT, VT, DV]':
Expand All @@ -88,8 +92,8 @@ def reverse(self) -> 'UDict[KT, VT, DV]':
def reversed(self) -> 'UDict[KT, VT, DV]':
keys, values = list(self.__dict.keys())[::-1], list(self.__dict.values())[::-1]
return UDict(dict(list(zip(keys, values))))
def __neg__(self) -> 'UDict[KT, VT, DV]':

def __invert__(self) -> 'UDict[KT, VT, DV]':
return self.reversed()

def __reversed__(self) -> 'UDict[KT, VT, DV]':
Expand Down

0 comments on commit 5b2db39

Please sign in to comment.