-
-
Save mikofski/6172160 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
import math | |
SAFE_FX = { | |
'exp': math.exp, | |
} | |
SAFE_NODES = set( | |
(ast.Expression, | |
ast.Num, | |
ast.Call, | |
ast.Name, | |
ast.Load, | |
ast.BinOp, | |
ast.Add, | |
ast.Sub, | |
ast.Mult, | |
ast.Div,) | |
) | |
class CleansingNodeVisitor(ast.NodeVisitor): | |
def generic_visit(self, node): | |
if type(node) not in SAFE_NODES: | |
raise Exception("%s not in SAFE_NODES" % type(node)) | |
super(CleansingNodeVisitor, self).generic_visit(node) | |
def visit_Call(self, call): | |
if call.func.id not in SAFE_FX: | |
raise Exception("Unknown function: %s" % call.func.id) | |
def safe_eval(s): | |
tree = ast.parse(s, mode='eval') | |
cnv = CleansingNodeVisitor() | |
cnv.visit(tree) | |
compiled = compile(tree, s, "eval") | |
return(eval(compiled, SAFE_FX)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment