8000 py/builtinimport: Allow builtin modules to be packages. · micropython/micropython@d91abfb · GitHub
[go: up one dir, main page]

Skip to content

Commit d91abfb

Browse files
committed
py/builtinimport: Allow builtin modules to be packages.
To use this, a built-in can add a submodule as a member of its globals dict. The submodule should call itself foo.bar, but this is not strictly necessary, and requires using qstrdefs(port).h to make the qstr. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
1 parent 4d2a04b commit d91abfb

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

py/builtinimport.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,20 @@ STATIC mp_obj_t process_import_at_level(qstr full_mod_name, qstr level_mod_name,
414414
} else {
415415
DEBUG_printf("Searching for sub-module\n");
416416

417+
#if MICROPY_MODULE_BUILTIN_SUBPACKAGES
418+
// If the outer module is a builtin (because its map is in ROM), then
419+
// treat it like a package if it contains this submodule in its
420+
// globals dict.
421+
mp_obj_module_t *mod = MP_OBJ_TO_PTR(outer_module_obj);
422+
if (mod->globals->map.is_fixed) {
423+
elem = mp_map_lookup(&mod->globals->map, MP_OBJ_NEW_QSTR(level_mod_name), MP_MAP_LOOKUP);
424+
// Also verify that the entry in the globals dict is in fact a module.
425+
if (elem && mp_obj_is_type(elem->value, &mp_type_module)) {
426+
return elem->value;
427+
}
428+
}
429+
#endif
430+
417431
// If the outer module is a package, it will have __path__ set.
418432
// We can use that as the path to search inside.
419433
mp_obj_t dest[2];

py/mpconfig.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -850,6 +850,13 @@ typedef double mp_float_t;
850850
#define MICROPY_MODULE_BUILTIN_INIT (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES)
851851
#endif
852852

853+
// Whether to allow built-in modules to have sub-packages (by making the
854+
// sub-package a member of their locals dict). The sub-package __name__ must
855+
// be foo.bar, and only top-level modules may have __init__.
856+
#ifndef MICROPY_MODULE_BUILTIN_SUBPACKAGES
857+
#define MICROPY_MODULE_BUILTIN_SUBPACKAGES (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING)
858+
#endif
859+
853860
// Whether to support module-level __getattr__ (see PEP 562)
854861
#ifndef MICROPY_MODULE_GETATTR
855862
#define MICROPY_MODULE_GETATTR (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES)

0 commit comments

Comments
 (0)
0