@@ -29,22 +29,35 @@ def flatten_grouping(grouping, schema=None):
2929
3030 :return: list of the scalar values in the input grouping
3131 """
32+ stack = []
33+ result = []
34+
35+ # Avoid repeated recursive Python calls by using an explicit stack
36+ push = stack .append
37+ pop = stack .pop
38+
39+ # Only validate once at the top if schema is provided
3240 if schema is None :
3341 schema = grouping
3442 else :
3543 validate_grouping (grouping , schema )
3644
37- if isinstance (schema , (tuple , list )):
38- return [
39- g
40- for group_el , schema_el in zip (grouping , schema )
41- for g in flatten_grouping (group_el , schema_el )
42- ]
43-
44- if isinstance (schema , dict ):
45- return [g for k in schema for g in flatten_grouping (grouping [k ], schema [k ])]
46-
47- return [grouping ]
45+ push ((grouping , schema ))
46+ while stack :
47+ group , sch = pop ()
48+ # Inline isinstance checks for perf
49+ typ = type (sch )
50+ if typ is tuple or typ is list :
51+ # Avoid double recursion / excessive list construction
52+ for ge , se in zip (group , sch ):
53+ push ((ge , se ))
54+ elif typ is dict :
55+ for k in sch :
56+ push ((group [k ], sch [k ]))
57+ else :
58+ result .append (group )
59+ result .reverse () # Since we LIFO, leaf values are in reverse order
60+ return result
4861
4962
5063def grouping_len (grouping ):
@@ -215,7 +228,6 @@ def validate_grouping(grouping, schema, full_schema=None, path=()):
215228 elif isinstance (schema , dict ):
216229 SchemaTypeValidationError .check (grouping , full_schema , path , dict )
217230 SchemaKeysValidationError .check (grouping , full_schema , path , set (schema ))
218-
219231 for k in schema :
220232 validate_grouping (
221233 grouping [k ], schema [k ], full_schema = full_schema , path = path + (k ,)
0 commit comments