我担心这是解决问题的一种混乱方式,但......
假设我想根据某些条件在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
Run Code Online (Sandbox Code Playgroud)
现在我如何才能在全球范围内提供导入的模块?
例如:
conditional_import_modules(test='bar')
thirdmodule.myfunction()
Run Code Online (Sandbox Code Playgroud) 我正在尝试从函数内部导入一个模块,并使其可用于我的整个文件,就像我在任何函数之外和所有其他代码之前导入一样.它在函数中的原因是因为我没有太多控制脚本的结构.这是否可能不诉诸于黑客__builtin__或传递我需要的所有代码?