如何从函数中进行全局导入?
发布于 2021-01-29 18:40:39
我担心这是解决问题的麻烦方式,但是…
假设我想根据某些条件在Python中进行一些导入。
因此,我想编写一个函数:
def conditional_import_modules(test):
if test == 'foo':
import onemodule, anothermodule
elif test == 'bar':
import thirdmodule, and_another_module
else:
import all_the_other_modules
现在如何使导入的模块全局可用?
例如:
conditional_import_modules(test='bar')
thirdmodule.myfunction()
关注者
0
被浏览
53
1 个回答
-
导入的模块只是变量-名称绑定到某些值。因此,您所需要做的就是导入它们,并使用
global
关键字使它们成为全局的。例:
>>> math Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'math' is not defined >>> def f(): ... global math ... import math ... >>> f() >>> math <module 'math' from '/usr/local/lib/python2.6/lib-dynload/math.so'>