从 .使用__import__导入x? [英] from . import x using __import__?
问题描述
如何从实现.使用
(从当前包中导入模块x)? __ import __
导入x
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
如何使用 __ import __
完成此操作?
推荐答案
__ import __
内置的语义与解释器从 import
语句生成的字节码相吻合,对于手动使用而言不是特别方便.如果我正确理解您要做什么,就可以满足您的要求:
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)
在具有 importlib
的Python版本中,您可能也可以说服 importlib.import_module
来做您想做的事,而不会带来太多麻烦,但是我不确定是否可以从中获取"".
"这样的语义.
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.
这篇关于从 .使用__import__导入x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!