diff --git a/quam/core/quam_classes.py b/quam/core/quam_classes.py index 7e2455c3..6ec8611c 100644 --- a/quam/core/quam_classes.py +++ b/quam/core/quam_classes.py @@ -787,6 +787,28 @@ def get_attrs( # TODO implement reference kwargs return self.data + def get_attr_name(self, attr_val: Any) -> Union[str, int]: + """Get the name of an attribute that matches the value. + + Args: + attr_val: The value of the attribute. + + Returns: + The name of the attribute. This can also be an int depending on the dict key + + Raises: + AttributeError if not found. + """ + for attr_name in self._get_attr_names(): + if attr_name in self and self[attr_name] is attr_val: + return attr_name + else: + raise AttributeError( + "Could not find name corresponding to attribute.\n" + f"attribute: {attr_val}\n" + f"obj: {self}" + ) + def _val_matches_attr_annotation(self, attr: str, val: Any) -> bool: """Check whether the type of an attribute matches the annotation. diff --git a/tests/quam_base/test_quam_dict.py b/tests/quam_base/test_quam_dict.py index ea0980df..b7fdea22 100644 --- a/tests/quam_base/test_quam_dict.py +++ b/tests/quam_base/test_quam_dict.py @@ -211,3 +211,21 @@ def test_quam_dict_int_keys(): assert quam_dict.data == {} with pytest.raises(KeyError): quam_dict[1] + + +def test_quam_dict_get_attr_int(): + quam_dict = QuamDict({1: 2}) + assert quam_dict.get_attr_name(2) == 1 + + +def test_quam_dict_print_summary(): + quam_dict = QuamDict({"a": "b", 1: 2}) + + from contextlib import redirect_stdout + import io + + f = io.StringIO() + with redirect_stdout(f): + quam_dict.print_summary() + s = f.getvalue() + assert s == 'QuamDict (parent unknown):\n a: "b"\n 1: 2\n'