from . import x using __import__?

对着背影说爱祢 提交于 2021-01-27 18:54:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!