Skip to content

Commit

Permalink
Allow QuamDict.get_attr_name to be an int
Browse files Browse the repository at this point in the history
  • Loading branch information
nulinspiratie committed Mar 8, 2024
1 parent 2601ae3 commit ef55191
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
22 changes: 22 additions & 0 deletions quam/core/quam_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 18 additions & 0 deletions tests/quam_base/test_quam_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'

0 comments on commit ef55191

Please sign in to comment.