Skip to content

Commit acf9bd0

Browse files
committed
Add asdict method and test
1 parent dd82a34 commit acf9bd0

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

fgpyo/util/metric.py

+9
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,15 @@ def values(self) -> Iterator[Any]:
149149
for field in inspect.get_fields(self.__class__): # type: ignore[arg-type]
150150
yield getattr(self, field.name)
151151

152+
def asdict(self) -> Dict[str, Any]:
153+
"""
154+
A dictionary mapping attribute names to values, inserted in the same order as the header.
155+
"""
156+
return {
157+
field.name: getattr(self, field.name)
158+
for field in inspect.get_fields(self.__class__) # type: ignore[arg-type]
159+
}
160+
152161
def formatted_values(self) -> List[str]:
153162
"""An iterator over formatted attribute values in the same order as the header."""
154163
return [self.format_value(value) for value in self.values()]

fgpyo/util/tests/test_metric.py

+5
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,11 @@ def test_metric_values(data_and_classes: DataBuilder) -> None:
391391
assert list(data_and_classes.Person(name="name", age=42).values()) == ["name", 42]
392392

393393

394+
@pytest.mark.parametrize("data_and_classes", (attr_data_and_classes, dataclasses_data_and_classes))
395+
def test_metric_asdict(data_and_classes: DataBuilder) -> None:
396+
assert data_and_classes.Person(name="name", age=42).asdict() == {"name": "name", "age": 42}
397+
398+
394399
@pytest.mark.parametrize("data_and_classes", (attr_data_and_classes, dataclasses_data_and_classes))
395400
def test_metric_parse(data_and_classes: DataBuilder) -> None:
396401
Person: TypeAlias = data_and_classes.Person

0 commit comments

Comments
 (0)