Skip to content

Commit a8d404e

Browse files
committed
Merge branch 'master' of github.com:micropython/micropython
2 parents 099a9cb + 2aa217b commit a8d404e

2 files changed

Lines changed: 27 additions & 3 deletions

File tree

py/builtinevex.c

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,26 @@ STATIC mp_obj_t mp_builtin_eval(mp_obj_t o_in) {
5757

5858
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_eval_obj, mp_builtin_eval);
5959

60-
STATIC mp_obj_t mp_builtin_exec(mp_obj_t o_in) {
61-
return parse_compile_execute(o_in, MP_PARSE_FILE_INPUT);
60+
STATIC mp_obj_t mp_builtin_exec(uint n_args, const mp_obj_t *args) {
61+
// Unconditional getting/setting assumes that these operations
62+
// are cheap, which is the case when this comment was written.
63+
mp_map_t *old_globals = rt_globals_get();
64+
mp_map_t *old_locals = rt_locals_get();
65+
if (n_args > 1) {
66+
mp_obj_t globals = args[1];
67+
mp_obj_t locals;
68+
if (n_args > 2) {
69+
locals = args[2];
70+
} else {
71+
locals = globals;
72+
}
73+
rt_globals_set(mp_obj_dict_get_map(globals));
74+
rt_locals_set(mp_obj_dict_get_map(locals));
75+
}
76+
mp_obj_t res = parse_compile_execute(args[0], MP_PARSE_FILE_INPUT);
77+
rt_globals_set(old_globals);
78+
rt_locals_set(old_locals);
79+
return res;
6280
}
6381

64-
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_exec_obj, mp_builtin_exec);
82+
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_exec_obj, 1, 3, mp_builtin_exec);

tests/basics/exec1.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
print(exec("def foo(): return 42"))
2+
print(foo())
3+
4+
d = {}
5+
exec("def bar(): return 84", d)
6+
print(d["bar"]())

0 commit comments

Comments
 (0)