@@ -31,6 +31,7 @@ def eval_conditional(*conds: List[Tuple[bool, Any]]) -> Any:
31
31
return val
32
32
33
33
34
+ # (takes_list, func)
34
35
funcs = {'max' : (True , max ),
35
36
'min' : (True , min ),
36
37
'len' : (True , len ),
@@ -43,7 +44,7 @@ class UnsetValueException(Exception):
43
44
pass
44
45
45
46
46
- def eval_expr (expr : str , ** kwargs ) -> Any :
47
+ def eval_expr (expr : str , _distribute = True , ** kwargs ) -> Any :
47
48
"""
48
49
Evaluates a given expression, with restricted syntax
49
50
@@ -82,6 +83,9 @@ def eval_expr(expr: str, **kwargs) -> Any:
82
83
- Similarly `strlen(container.persons.name)` will return a list whose members are the lengths of all names
83
84
84
85
:param expr: expression to evaluate
86
+ :param _distribute: if True, distribute operations over collections and return array
87
+ :param kwargs: variables to substitute
88
+ :return: result of evaluation
85
89
"""
86
90
#if kwargs:
87
91
# expr = expr.format(**kwargs)
@@ -90,13 +94,15 @@ def eval_expr(expr: str, **kwargs) -> Any:
90
94
return None
91
95
else :
92
96
try :
93
- return eval_ (ast .parse (expr , mode = 'eval' ).body , kwargs )
97
+ return eval_ (ast .parse (expr , mode = 'eval' ).body , kwargs , distribute = _distribute )
94
98
except UnsetValueException :
95
99
return None
96
100
97
101
98
102
99
- def eval_ (node , bindings = {}):
103
+ def eval_ (node , bindings = None , distribute = True ):
104
+ if bindings is None :
105
+ bindings = {}
100
106
if isinstance (node , ast .Num ):
101
107
return node .n
102
108
elif isinstance (node , ast .Str ):
@@ -123,7 +129,7 @@ def eval_(node, bindings={}):
123
129
# e.g. for person.name, this returns the val of person
124
130
v = eval_ (node .value , bindings )
125
131
# lookup attribute, potentially distributing the results over collections
126
- def _get (obj : Any , k : str , recurse = True ) -> Any :
132
+ def _get (obj : Any , k : str , recurse = distribute ) -> Any :
127
133
if isinstance (obj , dict ):
128
134
# dicts are treated as collections; distribute results
129
135
if recurse :
0 commit comments