How to check if a module is imported

大城市里の小女人 提交于 2020-02-25 03:58:07

问题


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.

How can I check if any module such as numpy imported?


回答1:


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

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. [...]

[The Python Language Reference: the import system]




回答2:


You can use sys.modules in the sys module for this:

>>> import sys
>>> import numpy
>>> 'numpy' in sys.modules
True

So your function could be:

def is_imported(module):
    return module in sys.modules

From the comments, you also wanted to return True if you'd used

from skimage.morphology import watershed

You can check if a function is in the current namespace by using dir()

>>> 'watershed' in dir()
False
>>> from skimage.morphology import watershed
>>> 'watershed' in dir()
True

To import a module using a string, you can use importlib.import_module():

>>> import importlib
>>> importlib.import_module('numpy')


来源:https://stackoverflow.com/questions/59271953/how-to-check-if-a-module-is-imported

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!