8000 py/builtinevex: Fix setting globals for native functions in compile(). · micropython/micropython@3db2910 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3db2910

Browse files
committed
py/builtinevex: Fix setting globals for native functions in compile().
Signed-off-by: Damien George <damien@micropython.org>
1 parent 916ceec commit 3db2910

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

py/builtinevex.c

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,13 @@ STATIC mp_obj_t code_execute(mp_obj_code_t *self, mp_obj_dict_t *globals, mp_obj
5757
// set exception handler to restore context if an exception is raised
5858
nlr_push_jump_callback(&ctx.callback, mp_globals_locals_set_from_nlr_jump_callback);
5959

60-
// a bit of a hack: fun_bc will re-set globals, so need to make sure it's
61-
// the correct one
62-
if (mp_obj_is_type(self->module_fun, &mp_type_fun_bc)) {
60+
// The call to mp_parse_compile_execute() in mp_builtin_compile() below passes
61+
// NULL for the globals, so repopulate that entry now with the correct globals.
62+
if (mp_obj_is_type(self->module_fun, &mp_type_fun_bc)
63+
#if MICROPY_EMIT_NATIVE
64+
|| mp_obj_is_type(self->module_fun, &mp_type_fun_native)
65+
#endif
66+
) {
6367
mp_obj_fun_bc_t *fun_bc = MP_OBJ_TO_PTR(self->module_fun);
6468
((mp_module_context_t *)fun_bc->context)->module.globals = globals;
6569
}

tests/basics/builtin_compile.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ def test():
2929
exec(compile("print(10 + 2)", "file", "single"))
3030
print(eval(compile("10 + 3", "file", "eval")))
3131

32+
# test accessing a function's globals from within a compile
33+
exec(compile("def func():pass\nprint('x', func.__globals__['x'])", "file", "exec"))
34+
3235
# bad mode
3336
try:
3437
compile('1', 'file', '')

0 commit comments

Comments
 (0)
0