如何检查模块是否已导入 [英] How to check if a module is imported

查看:92
本文介绍了如何检查模块是否已导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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. [...]

[ Python语言参考:导入系统]

这篇关于如何检查模块是否已导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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