Skip to content

Commit

Permalink
Preserve schema key order when flattening a dict grouping (#1701)
Browse files Browse the repository at this point in the history
* Preserve schema key order when flattening a dict grouping
* Python 3.6 compatibility
  • Loading branch information
jonmmease authored Aug 6, 2021
1 parent 71401b5 commit a19c274
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 9 deletions.
8 changes: 3 additions & 5 deletions dash/_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ def flatten_grouping(grouping, schema=None):
"""
if schema is None:
schema = grouping
else:
validate_grouping(grouping, schema)

if isinstance(schema, (tuple, list)):
return [
Expand All @@ -39,11 +41,7 @@ def flatten_grouping(grouping, schema=None):
]

if isinstance(schema, dict):
return [
g
for group_el, schema_el in zip(grouping.values(), schema.values())
for g in flatten_grouping(group_el, schema_el)
]
return [g for k in schema for g in flatten_grouping(grouping[k], schema[k])]

return [grouping]

Expand Down
5 changes: 1 addition & 4 deletions dash/dash.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
from . import _watch
from ._grouping import (
flatten_grouping,
validate_grouping,
map_grouping,
make_grouping_by_index,
grouping_len,
Expand Down Expand Up @@ -1075,11 +1074,9 @@ def add_context(*args, **kwargs):
# list or tuple
output_value = list(output_value)

# Flatten grouping and validate grouping structure
flat_output_values = flatten_grouping(output_value, output)

# Validate grouping structure
validate_grouping(output_value, output)

_validate.validate_multi_return(
output_spec, flat_output_values, callback_id
)
Expand Down
11 changes: 11 additions & 0 deletions tests/unit/dash/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,17 @@ def test_flatten_dict(dict_grouping_size):
assert len(result) == grouping_len(grouping)


def test_flatten_dict_key_order(dict_grouping_size):
grouping, size = dict_grouping_size
expected = list(range(size))

# Reverse key order of value dict to make sure order is preserved
rev_grouping = {k: grouping[k] for k in reversed(list(grouping.keys()))}
result = flatten_grouping(rev_grouping, grouping)
assert expected == result
assert len(result) == grouping_len(grouping)


def test_flatten_mixed(mixed_grouping_size):
grouping, size = mixed_grouping_size
expected = list(range(size))
Expand Down

0 comments on commit a19c274

Please sign in to comment.