fix execute_code()
@@ -7,9 +7,8 @@ def format_exception(e: Exception) -> str:
async def execute_code(code: str, env: dict) -> object:
- code_parsed = ast.parse("async def _eval_code():\n" + "\n".join(f" {i}" for i in code.splitlines()))
-
def insert_returns(body):
+ try:
if isinstance(body[-1], ast.Expr):
body[-1] = ast.Return(body[-1].value)
ast.fix_missing_locations(body[-1])
@@ -20,8 +19,14 @@ async def execute_code(code: str, env: dict) -> object:
if isinstance(body[-1], ast.With):
insert_returns(body[-1].body)
+ except IndexError:
+ pass
+
+ func_content = '\n'.join(f' {line}' for line in code.strip('\n').splitlines())
+ code = f'async def _execute_code():\n{func_content}'
- insert_returns(code_parsed.body[0].body)
+ parsed = ast.parse(code)
+ insert_returns(parsed.body[0].body)
- exec(compile(code_parsed, filename="<ast>", mode="exec"), env)
- return await eval("_eval_code()", env)
+ exec(compile(parsed, filename="<ast>", mode="exec"), env)
+ return await eval("_execute_code()", env)
