py/builtinimport: Support relative import in custom __import__ callback.

The globals need to be forwarded from the caller's context.

Signed-off-by: Damien George <damien@micropython.org>
This commit is contained in:
Chris Liechti
2020-11-30 16:40:56 +01:00
committed by Damien George
parent c07fda73f7
commit 48d96b400e
4 changed files with 42 additions and 6 deletions

View File

@@ -20,3 +20,12 @@ try:
__import__("xyz", None, None, None, -1)
except ValueError:
print("ValueError")
# globals is not checked for level=0
__import__("builtins", "globals")
# globals must be a dict (or None) for level>0
try:
__import__("builtins", "globals", None, None, 1)
except TypeError:
print("TypeError")

View File

@@ -0,0 +1,18 @@
# test overriding __import__ combined with importing from the filesystem
def custom_import(name, globals, locals, fromlist, level):
if level > 0:
print("import", name, fromlist, level)
return orig_import(name, globals, locals, fromlist, level)
orig_import = __import__
try:
__import__("builtins").__import__ = custom_import
except AttributeError:
print("SKIP")
raise SystemExit
# import calls __import__ behind the scenes
import pkg7.subpkg1.subpkg2.mod3