diff --git a/py/builtinimport.c b/py/builtinimport.c
index 467a27897c583479c98e4637459ddfecfabdad2d..debf75fd4d39f3fcc40c7ed1e5643c7cb28ec160 100644
--- a/py/builtinimport.c
+++ b/py/builtinimport.c
@@ -120,6 +120,9 @@ STATIC void do_load(mp_obj_t module_obj, vstr_t *file) {
     // set the new context
     mp_locals_set(mp_obj_module_get_globals(module_obj));
     mp_globals_set(mp_obj_module_get_globals(module_obj));
+    #if MICROPY_PY___FILE__
+    mp_store_attr(module_obj, MP_QSTR___file__, mp_obj_new_str(vstr_str(file), vstr_len(file), false));
+    #endif
 
     // parse the imported script
     mp_parse_error_kind_t parse_error_kind;
diff --git a/py/mpconfig.h b/py/mpconfig.h
index 99d697f9adc39ae98bb7a88b59de2ae8fd398ec7..bb1c0b5fe7be7b24b77ce9f52285ddd826b91679 100644
--- a/py/mpconfig.h
+++ b/py/mpconfig.h
@@ -279,6 +279,11 @@ typedef double mp_float_t;
 #define MICROPY_PY_BUILTINS_PROPERTY (1)
 #endif
 
+// Whether to set __file__ for imported modules
+#ifndef MICROPY_PY___FILE__
+#define MICROPY_PY___FILE__ (1)
+#endif
+
 // Whether to provide "array" module. Note that large chunk of the
 // underlying code is shared with "bytearray" builtin type, so to
 // get real savings, it should be disabled too.
diff --git a/py/qstrdefs.h b/py/qstrdefs.h
index 0deb646c7b885455ea82a46aab4d965e01258e1a..27b695722c64d61b7bc68e3a7a121c40709f2eba 100644
--- a/py/qstrdefs.h
+++ b/py/qstrdefs.h
@@ -43,6 +43,9 @@ Q(__next__)
 Q(__qualname__)
 Q(__path__)
 Q(__repl_print__)
+#if MICROPY_PY___FILE__
+Q(__file__)
+#endif
 
 Q(__bool__)
 Q(__contains__)
diff --git a/tests/import/import_file.py b/tests/import/import_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb9a88a706ec6db9456424602a4589014db67636
--- /dev/null
+++ b/tests/import/import_file.py
@@ -0,0 +1,2 @@
+import import1b
+print(import1b.__file__)
diff --git a/unix/main.c b/unix/main.c
index d0222de0d1c8a4ec34a6ae91f52def1ba2a9c77a..03718c22e5b510cb57f8b8d213ca90c09bda1d02 100644
--- a/unix/main.c
+++ b/unix/main.c
@@ -95,6 +95,11 @@ STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind,
     }
 
     qstr source_name = mp_lexer_source_name(lex);
+    #if MICROPY_PY___FILE__
+    if (input_kind == MP_PARSE_FILE_INPUT) {
+        mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
+    }
+    #endif
     mp_lexer_free(lex);
 
     /*