Skip to content

Commit

Permalink
py/builtinevex: Fix setting globals for native functions in compile().
Browse files Browse the repository at this point in the history
Signed-off-by: Damien George <[email protected]>
  • Loading branch information
dpgeorge committed Feb 20, 2024
1 parent 916ceec commit 3db2910
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
10 changes: 7 additions & 3 deletions py/builtinevex.c
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,13 @@ STATIC mp_obj_t code_execute(mp_obj_code_t *self, mp_obj_dict_t *globals, mp_obj
// set exception handler to restore context if an exception is raised
nlr_push_jump_callback(&ctx.callback, mp_globals_locals_set_from_nlr_jump_callback);

// a bit of a hack: fun_bc will re-set globals, so need to make sure it's
// the correct one
if (mp_obj_is_type(self->module_fun, &mp_type_fun_bc)) {
// The call to mp_parse_compile_execute() in mp_builtin_compile() below passes
// NULL for the globals, so repopulate that entry now with the correct globals.
if (mp_obj_is_type(self->module_fun, &mp_type_fun_bc)
#if MICROPY_EMIT_NATIVE
|| mp_obj_is_type(self->module_fun, &mp_type_fun_native)
#endif
) {
mp_obj_fun_bc_t *fun_bc = MP_OBJ_TO_PTR(self->module_fun);
((mp_module_context_t *)fun_bc->context)->module.globals = globals;
}
Expand Down
3 changes: 3 additions & 0 deletions tests/basics/builtin_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ def test():
exec(compile("print(10 + 2)", "file", "single"))
print(eval(compile("10 + 3", "file", "eval")))

# test accessing a function's globals from within a compile
exec(compile("def func():pass\nprint('x', func.__globals__['x'])", "file", "exec"))

# bad mode
try:
compile('1', 'file', '')
Expand Down

0 comments on commit 3db2910

Please sign in to comment.