Skip to content

Instantly share code, notes, and snippets.

@anch0vy
Last active February 14, 2016 13:36
Show Gist options
  • Save anch0vy/5a18195314c76a93f161 to your computer and use it in GitHub Desktop.
Save anch0vy/5a18195314c76a93f161 to your computer and use it in GitHub Desktop.
safecalc
def safe_calc(chat):
import ast
try:
tree = ast.parse(chat)
except SyntaxError:
return None
for node in ast.walk(tree):
for instance in [ast.Call,ast.Exec,ast.Import,ast.ImportFrom,ast.FunctionDef,ast.Lambda,ast.ClassDef]:
if isinstance(node,instance):
return None
if isinstance(node,ast.Attribute):
if node.attr.startswith('__'):
return None
if isinstance(node,ast.Name):
if node.id.startswith('__'):
return None
return eval(chat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment