From 6185757e292c4ace06d4c84b1b3a9a7b3a455c2e Mon Sep 17 00:00:00 2001 From: bleudev Date: Wed, 29 May 2024 11:47:17 +0300 Subject: [PATCH] add get.value param --- tests/test_udict.py | 4 ++++ ufpy/udict.py | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/tests/test_udict.py b/tests/test_udict.py index cc0ba55..bbdd55b 100644 --- a/tests/test_udict.py +++ b/tests/test_udict.py @@ -85,6 +85,10 @@ def test_get(self): self.assertEqual(d.get(index=2), d.get(key=4)) self.assertEqual(d.get(index=3), d.get(key=1)) + self.assertEqual(d.get(value=1), 2) + self.assertEqual(d.get(value=91), 4) + self.assertEqual(d.get(value=12), 1) + def test_len_and_iter(self): d = UDict(hello=1, hi=2) self.assertEqual(len(d), 2) diff --git a/ufpy/udict.py b/ufpy/udict.py index ea9db2b..45876a9 100644 --- a/ufpy/udict.py +++ b/ufpy/udict.py @@ -144,20 +144,50 @@ 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: + @overload + def get(self, *, key: KT) -> VT | DV: ... + @overload + def get(self, *, index: int) -> VT | DV: ... + @overload + def get(self, *, value: VT) -> KT: ... + def get(self, *, key: KT | None = None, index: int | None = None, value: VT | None = None) -> KT | VT | DV: """ Get a value with key or it's index. + If value is defined, returns key + :param key: Key of value in dict (optional) :param index: Index of value in dict (optional) + :param value: Value in dict (optional) :return: Value or default value - :exception ValueError: You defined both key and index params + :exception ValueError: You defined 0 or 2 or 3 params + :exception IndexError: index is bigger that length of dict """ + if key and index and value: + raise ValueError( + 'You defined both key, index and value params. Please cancel the definition one of this params.' + ) + if not key and not index and not value: + raise ValueError( + "You don't defined neither key, not index, not value params." + + " Please cancel the definition one of this params." + ) + if key and value: + raise ValueError('You defined both key and value params. Please cancel the definition one of this 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 value: + raise ValueError( + 'You defined both index and value params. Please cancel the definition one of this params.' + ) + if index and index > len(self): raise IndexError('Index is bigger that length of UDict.') + + if value: + i = self.values.index(value) + return self.keys[i] return self[self.keys[index-1]] if index else self[key] # Len, iterator and reversed version