| import ast | |
| SAFE_NODES = ( | |
| ast.Module, | |
| ast.Assign, | |
| ast.Expr, | |
| ast.Call, | |
| ast.Name, | |
| ast.Load, | |
| ast.Constant, | |
| ast.BinOp, | |
| ast.Add, | |
| ast.Sub, | |
| ast.Mult, | |
| ast.Div, | |
| ast.Return, | |
| ast.FunctionDef, | |
| ast.arguments | |
| ) | |
| def safe_execute(code): | |
| tree = ast.parse(code) | |
| for node in ast.walk(tree): | |
| if not isinstance(node, SAFE_NODES): | |
| raise ValueError(f"Unsafe code detected: {type(node).__name__}") | |
| local_env = {} | |
| exec(compile(tree, "<sandbox>", "exec"), {"__builtins__": {}}, local_env) | |
| return local_env |