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

Add flatten method to AssetCard #931

Merged
merged 1 commit into from
Dec 20, 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
18 changes: 18 additions & 0 deletions src/fairseq2/assets/card.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,24 @@ def _set_field_value(self, path: list[str], value: object) -> None:

metadata[path[-1]] = value

def flatten(self) -> AssetCard:
"""
Flattens the metadata of this card and all its bases into a single one.
"""
all_metadata = []

card: AssetCard | None = self

while card is not None:
all_metadata.append(card._metadata)

card = card._base_card

for metadata in all_metadata[-2::-1]:
all_metadata[-1].update(metadata)

return AssetCard(self._name, all_metadata[-1])

def __repr__(self) -> str:
return repr(self._metadata)

Expand Down
21 changes: 21 additions & 0 deletions tests/unit/assets/test_card.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,24 @@ def test_set_raises_error_when_path_conflicts(self) -> None:
AssetCardError, match=r"^The 'test-card' asset card cannot have a field named 'field1.field2' due to path conflict at 'field1'\.$", # fmt: skip
):
self.card.field("field1").field("field2").set("foo")

def test_flatten_works(self) -> None:
card = self.card.flatten()

expected_metadata = {
"name": "test-card",
"field1": "foo1",
"field2": {
"sub-field2": "sub-foo2",
},
"field3": 3,
"field4": "",
"field5": [],
"field6": "invalid/filename",
"field7": [1, 3, 2],
"field8": [1, "b", 3],
"field9": "http://foo.com",
"field10": None,
}

assert card.metadata == expected_metadata
Loading