circuitpython/tests/import/import_broken.py
David Grayson a79a6ab364 py/builtinimport: Remove partially-loaded modules from sys.modules.
Prior to this commit, importing a module that exists but has a syntax error
or some other problem that happens at import time would result in a
potentially-incomplete module object getting added to sys.modules.
Subsequent imports would use that object, resulting in confusing error
messages that hide the root cause of the problem.

This commit fixes that issue by removing the failed module from sys.modules
using the new NLR callback mechanism.

Note that it is still important to add the module to sys.modules while the
import is happening so that we can support circular imports just like
CPython does.

Fixes issue #967.

Signed-off-by: David Grayson <davidegrayson@gmail.com>
2023-06-05 23:21:52 +10:00

33 lines
865 B
Python

import sys, pkg
# Modules we import are usually added to sys.modules.
print("pkg" in sys.modules)
try:
from broken.zerodiv import x
except Exception as e:
print(e.__class__.__name__)
# The broken module we tried to import should not be in sys.modules.
print("broken.zerodiv" in sys.modules)
# If we try to import the module again, the code should
# run again and we should get the same error.
try:
from broken.zerodiv import x
except Exception as e:
print(e.__class__.__name__)
# Import a module that successfully imports some other modules
# before importing the problematic module.
try:
import broken.pkg2_and_zerodiv
except ZeroDivisionError:
pass
print("pkg2" in sys.modules)
print("pkg2.mod1" in sys.modules)
print("pkg2.mod2" in sys.modules)
print("broken.zerodiv" in sys.modules)
print("broken.pkg2_and_zerodiv" in sys.modules)