Skip to content

Commit

Permalink
More reliable datasets to recipe conversion (#2472)
Browse files Browse the repository at this point in the history
Co-authored-by: Valeriu Predoi <valeriu.predoi@gmail.com>
  • Loading branch information
bouweandela and valeriupredoi authored Jan 20, 2025
1 parent 0dce90c commit 865ea7d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 17 deletions.
15 changes: 9 additions & 6 deletions esmvalcore/_recipe/from_datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
import itertools
import logging
import re
from collections.abc import Iterable, Mapping, Sequence
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Iterable, Mapping, Sequence
from typing import TYPE_CHECKING, Any, Dict

from nested_lookup import nested_delete

Expand Down Expand Up @@ -102,11 +103,13 @@ def _move_datasets_up(recipe: Recipe) -> Recipe:


def _to_frozen(item):
"""Return a frozen and sorted copy of nested dicts and lists."""
if isinstance(item, list):
return tuple(sorted(_to_frozen(elem) for elem in item))
if isinstance(item, dict):
return tuple(sorted((k, _to_frozen(v)) for k, v in item.items()))
"""Return a frozen copy of nested dicts and lists."""
if isinstance(item, str):
return item
if isinstance(item, Mapping):
return frozenset((k, _to_frozen(v)) for k, v in item.items())
if isinstance(item, Iterable):
return frozenset(_to_frozen(elem) for elem in item)
return item


Expand Down
33 changes: 22 additions & 11 deletions tests/unit/recipe/test_from_datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,35 @@ def test_to_frozen():
"d",
"c",
],
"bb": "dc",
},
}

result = _to_frozen(data)
expected = (
(
"a",
expected = frozenset(
{
(
(
"b",
(
"c",
"d",
),
"a",
frozenset(
{
(
"b",
frozenset(
{
"c",
"d",
}
),
),
(
"bb",
"dc",
),
}
),
),
),
("abc", "x"),
("abc", "x"),
}
)

assert result == expected
Expand Down

0 comments on commit 865ea7d

Please sign in to comment.