I am continuing the code for Ned Batchelder's byterun, a Python interpreter written in Python for Python versions other than Python 3.4. See x-python.
One of the long-standing concerns of this kind of approach is separating the interpreter namespace in imports from the interpreted program namespace.
Aside: Not separating the namespaces can be advantageous if you want fast interpreter which doesn't interpret into the imported modules, but separating the modules is more correct, although slower, and necessary when interpreting bytecode from a different Python version.
So when the interpreter encounters an IMPORT_NAME opcode, I would like to use importlib.util to basically have a copy of the module that is distinct from any import that the interpreter encounters.
The problem I have right now is these import differently and this can be seen using hasattr().
Here is an example:
import importlib
module_spec = importlib.util.find_spec("textwrap")
textwrap_module = importlib.util.module_from_spec(module_spec)
submodule = "fill"
print(hasattr(textwrap_module, submodule)) # False
import textwrap
print(hasattr(textwrap, submodule)) # True
How do I get the same behavior using importlib.util?
(I should note however that for sys, both can find the "path" submodule as an attribute of sys.)