Skip to content

Commit d9047d3

Browse files
committed
py/builtinimport: Support importing packages from compiled .mpy files.
This patch ensures that __init__.mpy files are imported if their containing directory is imported as a package.
1 parent d227620 commit d9047d3

1 file changed

Lines changed: 14 additions & 9 deletions

File tree

py/builtinimport.c

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -73,15 +73,8 @@ STATIC mp_import_stat_t mp_import_stat_any(const char *path) {
7373
return mp_import_stat(path);
7474
}
7575

76-
STATIC mp_import_stat_t stat_dir_or_file(vstr_t *path) {
76+
STATIC mp_import_stat_t stat_file_py_or_mpy(vstr_t *path) {
7777
mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
78-
DEBUG_printf("stat %s: %d\n", vstr_str(path), stat);
79-
if (stat == MP_IMPORT_STAT_DIR) {
80-
return stat;
81-
}
82-
83-
vstr_add_str(path, ".py");
84-
stat = mp_import_stat_any(vstr_null_terminated_str(path));
8578
if (stat == MP_IMPORT_STAT_FILE) {
8679
return stat;
8780
}
@@ -97,6 +90,18 @@ STATIC mp_import_stat_t stat_dir_or_file(vstr_t *path) {
9790
return MP_IMPORT_STAT_NO_EXIST;
9891
}
9992

93+
STATIC mp_import_stat_t stat_dir_or_file(vstr_t *path) {
94+
mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
95+
DEBUG_printf("stat %s: %d\n", vstr_str(path), stat);
96+
if (stat == MP_IMPORT_STAT_DIR) {
97+
return stat;
98+
}
99+
100+
// not a directory, add .py and try as a file
101+
vstr_add_str(path, ".py");
102+
return stat_file_py_or_mpy(path);
103+
}
104+
100105
STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *dest) {
101106
#if MICROPY_PY_SYS
102107
// extract the list of paths
@@ -463,7 +468,7 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
463468
mp_store_attr(module_obj, MP_QSTR___path__, mp_obj_new_str(vstr_str(&path), vstr_len(&path), false));
464469
vstr_add_char(&path, PATH_SEP_CHAR);
465470
vstr_add_str(&path, "__init__.py");
466-
if (mp_import_stat_any(vstr_null_terminated_str(&path)) != MP_IMPORT_STAT_FILE) {
471+
if (stat_file_py_or_mpy(&path) != MP_IMPORT_STAT_FILE) {
467472
vstr_cut_tail_bytes(&path, sizeof("/__init__.py") - 1); // cut off /__init__.py
468473
//mp_warning("%s is imported as namespace package", vstr_str(&path));
469474
} else {

0 commit comments

Comments
 (0)