eval.py 726 B

1234567891011121314
  1. # based on https://stackoverflow.com/a/39381428
  2. # Parses and executes a block of Python code, and returns the eval result of the last statement
  3. import ast
  4. def exec_then_eval(code, _globals={}, _locals={}):
  5. block = ast.parse(code, mode='exec')
  6. # assumes last node is an expression
  7. last = ast.Expression(block.body.pop().value)
  8. extended_globals = {
  9. '__builtins__': {'isinstance': isinstance, 'print': print, 'int': int, 'float': float, 'bool': bool, 'str': str, 'tuple': tuple, 'len': len, 'set': set, 'dict': dict },
  10. **_globals,
  11. }
  12. exec(compile(block, '<string>', mode='exec'), extended_globals, _locals)
  13. return eval(compile(last, '<string>', mode='eval'), extended_globals, _locals)