Skip to content

Commit 3c9c368

Browse files
committed
py: Add support to call __init__ from a builtin module on first import.
1 parent 408b74d commit 3c9c368

2 files changed

Lines changed: 16 additions & 0 deletions

File tree

py/mpconfig.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,11 @@ typedef double mp_float_t;
406406
#define MICROPY_STREAMS_NON_BLOCK (0)
407407
#endif
408408

409+
// Whether to call __init__ when importing builtin modules for the first time
410+
#ifndef MICROPY_MODULE_BUILTIN_INIT
411+
#define MICROPY_MODULE_BUILTIN_INIT (0)
412+
#endif
413+
409414
// Whether module weak links are supported
410415
#ifndef MICROPY_MODULE_WEAK_LINKS
411416
#define MICROPY_MODULE_WEAK_LINKS (0)

py/objmodule.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,17 @@ mp_obj_t mp_module_get(qstr module_name) {
215215
if (el == NULL) {
216216
return MP_OBJ_NULL;
217217
}
218+
219+
if (MICROPY_MODULE_BUILTIN_INIT) {
220+
// look for __init__ and call it if it exists
221+
mp_obj_t dest[2];
222+
mp_load_method_maybe(el->value, MP_QSTR___init__, dest);
223+
if (dest[0] != MP_OBJ_NULL) {
224+
mp_call_method_n_kw(0, 0, dest);
225+
// register module so __init__ is not called again
226+
mp_module_register(module_name, el->value);
227+
}
228+
}
218229
}
219230

220231
// module found, return it

0 commit comments

Comments
 (0)