Skip to content

Instantly share code, notes, and snippets.

@njvack
Created September 21, 2012 02:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save njvack/3759435 to your computer and use it in GitHub Desktop.
Save njvack/3759435 to your computer and use it in GitHub Desktop.
My stab at safe python evaluation
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))
@mikofski
Copy link

mikofski commented Aug 7, 2013

why not add a few more functions, like math.log, math.sin, &c., or maybe some numpy functions? this is super similar to JF Sebastians ast parser

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment