Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow QuamDict.get_attr_name to be an int #20

Merged
merged 1 commit into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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'