如何检查模块是否已导入 [英] How to check if a module is imported
问题描述
我使用numpy和scipy进行数据分析.我想在我定义的函数内编写代码,以便在调用该函数时检查例如是否导入了numpy,如果未导入,则应将其导入.
I use numpy and scipy for data analysis. I want to write a code inside a function that I define so that when the function is called it check if, for example, numpy is imported and if it is not imported, then it should import it.
如何检查是否导入了诸如numpy之类的模块?
How can I check if any module such as numpy imported?
推荐答案
import
语句是幂等的-它已检查模块是否已加载.在您的函数中使用import module
已经可以满足您的要求:
The import
statement is idempotent - it already checks whether the module has been loaded. Using import module
in your function already does what you want:
def my_func():
import numpy # load numpy if not available
# use numpy
这适用于所有类型的导入,包括子模块,相对导入和成员别名.
This works for all kinds of imports, including submodules, relative imports and aliasing of members.
def my_other_func():
# load skimage, skimage.morphology, and
# skimage.morphology.watershed if they are unimported modules
from skimage.morphology import watershed
在导入期间,在
sys.modules
中查找模块名称,如果存在,则关联的值是满足导入要求的模块,然后过程完成. [...]
During import, the module name is looked up in
sys.modules
and if present, the associated value is the module satisfying the import, and the process completes. [...]
这篇关于如何检查模块是否已导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!