@@ -29,22 +29,35 @@ def flatten_grouping(grouping, schema=None):
29
29
30
30
:return: list of the scalar values in the input grouping
31
31
"""
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
32
40
if schema is None :
33
41
schema = grouping
34
42
else :
35
43
validate_grouping (grouping , schema )
36
44
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
48
61
49
62
50
63
def grouping_len (grouping ):
@@ -215,7 +228,6 @@ def validate_grouping(grouping, schema, full_schema=None, path=()):
215
228
elif isinstance (schema , dict ):
216
229
SchemaTypeValidationError .check (grouping , full_schema , path , dict )
217
230
SchemaKeysValidationError .check (grouping , full_schema , path , set (schema ))
218
-
219
231
for k in schema :
220
232
validate_grouping (
221
233
grouping [k ], schema [k ], full_schema = full_schema , path = path + (k ,)
0 commit comments