问题
How do I achieve from . import x
(import module x from the current package), using __import__
?
Here are some attempts that failed:
>>> __import__('.', fromlist=['x'])
ValueError: Empty module name
>>> __import__('.x')
ValueError: Empty module name
How is this done using __import__
?
回答1:
The __import__ built-in's semantics are dovetailed with the bytecode that the interpreter generates from import
statements, and are not especially convenient for manual use. If I understand what you are going for correctly, this does what you want:
name = 'x'
mod = getattr(__import__('', fromlist=[name], level=1), name)
In versions of Python that have importlib, you might also be able to persuade importlib.import_module
to do what you want with less ugliness, but I am not sure it is possible to get "from .
" semantics that way.
回答2:
__import__(__name__, fromlist=['x'])
That should get you what you need.
来源:https://stackoverflow.com/questions/8408373/from-import-x-using-import