Skip to content

Commit f1c9e77

Browse files
committed
py/builtinimport: Call __init__ for modules imported via a weak link.
This is a bit of a clumsy way of doing it but solves the issue of __init__ not running when a module is imported via its weak-link name. Ideally a better solution would be found.
1 parent 479392a commit f1c9e77

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

py/builtinimport.c

+13
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,19 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
389389
}
390390
// found weak linked module
391391
module_obj = el->value;
392+
if (MICROPY_MODULE_BUILTIN_INIT) {
393+
// look for __init__ and call it if it exists
394+
// Note: this code doesn't work fully correctly because it allows the
395+
// __init__ function to be called twice if the module is imported by its
396+
// non-weak-link name. Also, this code is duplicated in objmodule.c.
397+
mp_obj_t dest[2];
398+
mp_load_method_maybe(el->value, MP_QSTR___init__, dest);
399+
if (dest[0] != MP_OBJ_NULL) {
400+
mp_call_method_n_kw(0, 0, dest);
401+
// register module so __init__ is not called again
402+
mp_module_register(mod_name, el->value);
403+
}
404+
}
392405
} else {
393406
no_exist:
394407
#else

0 commit comments

Comments
 (0)