Skip to content

Speed up function flatten_grouping by 330% #3303

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

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
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
40 changes: 27 additions & 13 deletions dash/_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,37 @@ def flatten_grouping(grouping, schema=None):

:return: list of the scalar values in the input grouping
"""
stack = []
result = []
pushed_validate = False

# Avoid repeated recursive Python calls by using an explicit stack
push = stack.append
pop = stack.pop

# Only validate once at the top if schema is provided
if schema is None:
schema = grouping
else:
validate_grouping(grouping, schema)

if isinstance(schema, (tuple, list)):
return [
g
for group_el, schema_el in zip(grouping, schema)
for g in flatten_grouping(group_el, schema_el)
]

if isinstance(schema, dict):
return [g for k in schema for g in flatten_grouping(grouping[k], schema[k])]

return [grouping]
pushed_validate = True # Just for clarity; not strictly necessary

push((grouping, schema))
while stack:
group, sch = pop()
# Inline isinstance checks for perf
typ = type(sch)
if typ is tuple or typ is list:
# Avoid double recursion / excessive list construction
for ge, se in zip(group, sch):
push((ge, se))
elif typ is dict:
for k in sch:
push((group[k], sch[k]))
else:
result.append(group)
result.reverse() # Since we LIFO, leaf values are in reverse order
return result


def grouping_len(grouping):
Expand Down Expand Up @@ -215,7 +230,6 @@ def validate_grouping(grouping, schema, full_schema=None, path=()):
elif isinstance(schema, dict):
SchemaTypeValidationError.check(grouping, full_schema, path, dict)
SchemaKeysValidationError.check(grouping, full_schema, path, set(schema))

for k in schema:
validate_grouping(
grouping[k], schema[k], full_schema=full_schema, path=path + (k,)
Expand Down