Skip to content

Commit

Permalink
get() and tests for get()
Browse files Browse the repository at this point in the history
  • Loading branch information
bleudev committed May 28, 2024
1 parent e3760d8 commit ceead0b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
14 changes: 14 additions & 0 deletions tests/test_udict.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,20 @@ def test_set_item(self):
d[:] = [1, 2]
self.assertDictEqual(d.dictionary, {'hello': 1, 'hi': 2})

def test_get(self):
d = UDict({2: 1, 4: 91, 1: 12})
self.assertEqual(d.get(index=1), d.get(key=2))
self.assertEqual(d.get(index=2), d.get(key=4))
self.assertEqual(d.get(index=3), d.get(key=1))

# TODO: test_del_item
# TODO: test_len_and_iter
# TODO: test_bool
# TODO: test_contains
# TODO: test_str_and_repr
# TODO: test_cmp_and_eq
# TODO: test_math_operations


if __name__ == '__main__':
unittest.main()
17 changes: 17 additions & 0 deletions ufpy/udict.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,23 @@ def __delitem__(self, key: KT | int | slice) -> None:

self.__dict = del_items_for_several_keys(self.__dict, keys)

# get
def get(self, *, key: KT | None = None, index: int | None = None) -> VT | DV:
"""
Get a value with key or it's index.
:param key: Key of value in dict (optional)
:param index: Index of value in dict (optional)
:return: Value or default value
:exception ValueError: You defined both key and index params
"""
if key and index:
raise ValueError('You defined both key and index params. Please cancel the definition one of this params.')
if index and index > len(self):
raise IndexError('Index is bigger that length of UDict.')
return self[self.keys[index-1]] if index else self[key]

# Len, iterator and reversed version
def __len__(self) -> int:
return len(self.items)
Expand Down

0 comments on commit ceead0b

Please sign in to comment.