从 .使用__import__导入x? [英] from . import x using __import__?

查看:57
本文介绍了从 .使用__import__导入x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从实现.使用 __ import __ 导入x (从当前包中导入模块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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆