From 139b3fc329eccb703ca21855a69c6aac70a72500 Mon Sep 17 00:00:00 2001 From: Matthew Wildoer Date: Thu, 26 Sep 2024 11:50:24 +0200 Subject: [PATCH] Core: Add backwards lookup and setdefault to FuncDict --- src/faebryk/libs/util.py | 6 ++++++ test/libs/test_util_func_collections.py | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/faebryk/libs/util.py b/src/faebryk/libs/util.py index 1a466795..1908a1db 100644 --- a/src/faebryk/libs/util.py +++ b/src/faebryk/libs/util.py @@ -1061,3 +1061,9 @@ def __repr__(self) -> str: f"{self.__class__.__name__}" f"({repr(list(self.items()))}, hasher={repr(self._hasher)})" ) + + def backwards_lookup(self, item: U) -> T: + for key, value in self.items(): + if value == item: + return key + raise KeyError(item) diff --git a/test/libs/test_util_func_collections.py b/test/libs/test_util_func_collections.py index d709b8e0..6dba9314 100644 --- a/test/libs/test_util_func_collections.py +++ b/test/libs/test_util_func_collections.py @@ -40,6 +40,21 @@ def test_func_dict_hash_collision(): assert a[2] == "b" +def test_func_dict_backwards_lookup(): + a = FuncDict() + a[1] = "a" + a[2] = "b" + assert a.backwards_lookup("a") == 1 + assert a.backwards_lookup("b") == 2 + + +def test_func_dict_setdefault(): + a = FuncDict() + assert 1 not in a + assert a.setdefault(1, "a") == "a" + assert a[1] == "a" + + def test_func_set_contains(): a = FuncSet([1, 2, 3, FuncDict, FuncSet]) assert 1 in a