14
14
15
15
BL_BUILTINS = ("breakpoint" , "classmethod" , "compile" , "delattr" , "eval" , "exec" , "exit" , "getattr" , "globals" , "help" ,
16
16
"hasattr" , "input" , "locals" , "memoryview" , "open" , "print" , "property" , "quit" , "staticmethod" , "super" )
17
+ COMP_NODES = ("DictComp" , "Lambda" , "ListComp" , "SetComp" , "GeneratorExp" )
17
18
WL_NODES = ("add" , "and" , "binop" , "bitand" , "bitor" , "bitxor" , "boolop" , "call" , "cmpop" , "compare" , "comprehension" ,
18
- "constant" , "dict" , "div" , "eq" , "expr" , "expr_context" , "expression" , "floordiv" , "for" , "generatorexp" ,
19
- "gt" , "gte" , "in" , "index" , "invert" , "is" , "isnot" , "list" , "listcomp" , "load" , "lshift" , "lt" , "lte" ,
20
- "matmult" , "mod" , "mult" , "name" , "nameconstant" , "not" , "noteq" , "notin" , "num" , "operator" , "or" , "pow" ,
21
- "rshift" , "set" , "slice" , "store" , "str" , "sub" , "subscript" , "tuple" , "uadd" , "unaryop" , "usub" )
19
+ "constant" , "dict" , "dictcomp" , "div" , "eq" , "expr" , "expr_context" , "expression" , "floordiv" , "for" ,
20
+ "generatorexp" , "gt" , "gte" , "in" , "index" , "invert" , "is" , "isnot" , "list" , "listcomp" , "load" , "lshift" ,
21
+ "lt" , "lte" , "matmult" , "mod" , "mult" , "name" , "nameconstant" , "not" , "noteq" , "notin" , "num" , "operator" ,
22
+ "or" , "pow" , "rshift" , "set" , "setcomp" , "slice" , "store" , "str" , "sub" , "subscript" , "tuple" , "uadd" ,
23
+ "unaryop" , "usub" )
22
24
23
25
24
26
set_exception ("ForbiddenNameError" , "NameError" )
@@ -40,7 +42,7 @@ def __eval(expr, globals=None, locals=None, bl_builtins=BL_BUILTINS, wl_nodes=WL
40
42
# walk the AST and only allow the whitelisted nodes
41
43
extra_names = []
42
44
for node in __walk (ast .parse (expr , mode = "eval" )):
43
- if any (n in list (map (lambda x : x .name , node .parents )) for n in ( "Lambda" , "ListComp" , "GeneratorExp" ) ) and \
45
+ if any (n in list (map (lambda x : x .name , node .parents )) for n in COMP_NODES ) and \
44
46
hasattr (node , "id" ) and node .id not in extra_names :
45
47
extra_names .append (node .id )
46
48
# blacklist dunders and input list
@@ -100,7 +102,7 @@ def eval_free_variables(expression, **variables):
100
102
"""
101
103
free_vars = []
102
104
for node in __walk (ast .parse (expression , mode = "eval" )):
103
- if any (n in list (map (lambda x : x .name , node .parents )) for n in ( "Lambda" , "ListComp" , "GeneratorExp" ) ) and \
105
+ if any (n in list (map (lambda x : x .name , node .parents )) for n in COMP_NODES ) and \
104
106
hasattr (node , "id" ) and node .id not in variables and node .id not in free_vars :
105
107
free_vars .append (node .id )
106
108
return free_vars
0 commit comments