Skip to content

Commit a3b787a

Browse files
committed
py/runtime: Add MICROPY_LAZY_LOAD_GLOBAL.
Allow ports to provide a lazy load function for undefined globals.
1 parent 4005760 commit a3b787a

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

py/mpconfig.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,14 @@ typedef double mp_float_t;
757757
#define MICROPY_CAN_OVERRIDE_BUILTINS (0)
758758
#endif
759759

760+
// Allow ports to provide a lazy load function for undefined globals
761+
// By enabling this, MicroPython will call mp_lazy_load_global() whenever an undefined
762+
// global is accessed. Ports can return a non-MP_OBJ_NULL value which will be returned instead
763+
// of raising NameError. It is also cached for faster future access.
764+
#ifndef MICROPY_LAZY_LOAD_GLOBAL
765+
#define MICROPY_LAZY_LOAD_GLOBAL (0)
766+
#endif
767+
760768
// Whether to check that the "self" argument of a builtin method has the
761769
// correct type. Such an explicit check is only needed if a builtin
762770
// method escapes to Python land without a first argument, eg

py/runtime.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,14 @@ mp_obj_t mp_load_global(qstr qst) {
184184
#endif
185185
elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
186186
if (elem == NULL) {
187+
#if MICROPY_LAZY_LOAD_GLOBAL
188+
mp_obj_t obj = mp_lazy_load_global(qst);
189+
if (obj != MP_OBJ_NULL) {
190+
// cache it for faster access next time
191+
mp_store_global(qst, obj);
192+
return obj;
193+
}
194+
#endif
187195
if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
188196
mp_raise_msg(&mp_type_NameError, "name not defined");
189197
} else {

py/runtime.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,9 @@ static inline void mp_globals_set(mp_obj_dict_t *d) { MP_STATE_THREAD(dict_globa
9393

9494
mp_obj_t mp_load_name(qstr qst);
9595
mp_obj_t mp_load_global(qstr qst);
96+
#ifdef MICROPY_LAZY_LOAD_GLOBAL
97+
mp_obj_t mp_lazy_load_global(qstr qst);
98+
#endif
9699
mp_obj_t mp_load_build_class(void);
97100
void mp_store_name(qstr qst, mp_obj_t obj);
98101
void mp_store_global(qstr qst, mp_obj_t obj);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy