Skip to content

Commit d0f5e61

Browse files
committed
py: Implement __file__ attribute for modules.
1 parent 645582f commit d0f5e61

File tree

5 files changed

+18
-0
lines changed

5 files changed

+18
-0
lines changed

py/builtinimport.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,9 @@ STATIC void do_load(mp_obj_t module_obj, vstr_t *file) {
120120
// set the new context
121121
mp_locals_set(mp_obj_module_get_globals(module_obj));
122122
mp_globals_set(mp_obj_module_get_globals(module_obj));
123+
#if MICROPY_PY___FILE__
124+
mp_store_attr(module_obj, MP_QSTR___file__, mp_obj_new_str(vstr_str(file), vstr_len(file), false));
125+
#endif
123126

124127
// parse the imported script
125128
mp_parse_error_kind_t parse_error_kind;

py/mpconfig.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,11 @@ typedef double mp_float_t;
279279
#define MICROPY_PY_BUILTINS_PROPERTY (1)
280280
#endif
281281

282+
// Whether to set __file__ for imported modules
283+
#ifndef MICROPY_PY___FILE__
284+
#define MICROPY_PY___FILE__ (1)
285+
#endif
286+
282287
// Whether to provide "array" module. Note that large chunk of the
283288
// underlying code is shared with "bytearray" builtin type, so to
284289
// get real savings, it should be disabled too.

py/qstrdefs.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ Q(__next__)
4343
Q(__qualname__)
4444
Q(__path__)
4545
Q(__repl_print__)
46+
#if MICROPY_PY___FILE__
47+
Q(__file__)
48+
#endif
4649

4750
Q(__bool__)
4851
Q(__contains__)

tests/import/import_file.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import import1b
2+
print(import1b.__file__)

unix/main.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,11 @@ STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind,
9595
}
9696

9797
qstr source_name = mp_lexer_source_name(lex);
98+
#if MICROPY_PY___FILE__
99+
if (input_kind == MP_PARSE_FILE_INPUT) {
100+
mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
101+
}
102+
#endif
98103
mp_lexer_free(lex);
99104

100105
/*

0 commit comments

Comments
 (0)