从A.B import X使用?

2024-06-01 04:21:23 发布

您现在位置:Python中文网/ 问答频道 /正文

假设A是一个包目录,B是目录中的模块,X是用B编写的函数或变量?以scipy为例:

我想要的:

from scipy.constants.constants import yotta

什么不起作用:

^{pr2}$

如有任何建议,将不胜感激。在


Tags: 模块函数fromimport目录scipy建议constants
2条回答

python import语句执行两个任务:加载模块并使其在命名空间中可用。在

import foo.bar.baz 

将在命名空间中提供名称foo,而不是baz,因此__import__将给您foo

^{pr2}$

另一方面

from foo.bar.baz import a, b

不使模块可用,但是import语句需要执行assignmaents是baz。这对应于

_tmp_baz = __import__('foo.bar.baz', fromlist=['a', 'b'])
a = _tmp_baz.a
b = _tmp_baz.b

当然,没有让临时的东西可见。在

__import__函数不强制ab,所以当你想要baz时,你可以在fromlist参数中给出任何东西来将__import__置于“from input”模式。在

所以解决办法如下。假设'yotta'是一个字符串变量,我已经使用getattr来访问属性。在

yotta = getattr(__import__('scipy.constants.constants', 
                           fromlist=['yotta']), 
                'yotta')
__import__("scipy.constants.constants", fromlist=["yotta"])

参数fromlist相当于from LHS import RHS的右侧。在


From the docs:

__import__(name[, globals[, locals[, fromlist[, level]]]])

[...]

The fromlist gives the names of objects or submodules that should be imported from the module given by name.

[...]

On the other hand, the statement from spam.ham import eggs, sausage as saus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage

(重点是我的。)

相关问题 更多 >