- How to check if a module is available for import?
- 6 Answers 6
- How do I check whether a module is installed in Python, and install it if needed?
- How to check does a file imports from another file in Python
- Update, i tried @Hessam Korki’s suggestion it doesn’t works.
- How to check if a module is imported
- 2 Answers 2
How to check if a module is available for import?
I am using a module in a script but one action inside the host application doesn’t load this module so the script fails. It’s fine if it fails because it doesn’t need to run, but I don’t want to see the error message box. Is there a way to check if the module is available, like:
isavailable ( mymodule ) # safe to use the module
Is this one of your own modules, or part of a package that was installed as a setuptools distribution?
Ok, then @kroolik’s answer is the way to go. (In case of a setuptools package it would have been better to check for pkg_resources.get_distribution(‘foobar’) )
6 Answers 6
try: import my_module except ImportError: available = False else: available = True
Wouldn’t this, in fact, import the module? I suppose you could define a function that does this e.g. def import_avail(module): try: __import__(module) except ImportError: return False else: return True but otherwise you’ll have one heck of a side effect!
@adsmith, you can move the try: import except: else: clause into eval and check for errors/sentinel variables. And yes, by importing you are exposing yourself to side-effects of the module’s init, but then, I would really reevaluate if I would use a module that fires a bomb on import.
Thanks, btw do you know if I can just halt the execution using return? I am not inside a function, but I want the rest of the commands that comes after not to be executed. Not sure how I could modify your code to do that. I guess I can just encapsulate the rest of the code in an if statement but it’s long.
@JoanVenge, I would go with raise ImportError(‘Module `my_module` is not available.’) and handle the ImportError in the importing module, but that depends on your use case. Sometimes you might want to mock my_module with my_module_compat when the prior is not available, try: import my_module except ImportError: import my_module_compat as my_module . my_module_compat would either implement a noop variant of my_module , or whole different implementation.
@kroolik: Why raise ImportError(…) ? You’re just handling ImportError by raising an almost-identical error with a different message…
import importlib def import_if_available(name, package=None): try: return importlib.import_module(name, package) except ImportError: return None print import_if_available('os.path')
The purpose of the importlib package is two-fold. One is to provide an implementation of the import statement (and thus, by extension, the import() function) in Python source code. This provides an implementation of import which is portable to any Python interpreter. This also provides a reference implementation which is easier to comprehend than one implemented in a programming language other than Python. Two, the components to implement import are exposed in this package, making it easier for users to create their own custom objects (known generically as an importer) to participate in the import process. Details on custom importers can be found in PEP 302.
Your answer also hardcodes the module name, and the question doesn’t indicate that the module name needs to be dynamic.
import_if_available(«namespace.package») — oops, doesn’t work. That’s why you shouldn’t use __import__ unless you really know what you’re doing.
The easiest way to check if a module is available is to import it. And this is almost always what you want, as well. If the module isn’t available, this will fail. If the module is available… well, the reason you’re checking is because you need to verify that you will be able to import it, so you’re not wasting any time importing it now.
More generally, in Python, it’s easier to ask forgiveness than permission. If you want to know whether you can do something, just try to do it.
So, this is almost an answer on its own:
The code will «early return, break the execution if it’s not available.» The only problem is that you don’t want to see the error message.
There are two ways around this.
First, you could wrap the code up like this:
try: import mymodule except ImportError: pass else: # everything else you were going to do.
Whether «the code» is the whole function body, or the line of code that calls the function, or a chunk of top-level code in your script or module, or whatever, it makes no difference.
If you want to avoid the extra block indent, you can «return early» in various different ways. (Although really, it’s almost always trivial to just extract all the indented code out into a new function, which means you end up with just a one-line function call being in the else block.)
How you do that depends on what level you’re trying to return from, and that isn’t clear from your question. If you want to return early from a function, just return (possibly with an appropriate value). If you want to return early from the whole program, just sys.exit(0) . So:
try: import mymodule except ImportError: sys.exit(0) # the rest of your code
You could also exit with a positive value, which is a way to tell the shell or whoever else called your program that it «failed», without printing out an error traceback.
How do I check whether a module is installed in Python, and install it if needed?
Warning: It is highly recommended to install python-modules using official Ubuntu repository only and not to use the pip method as superuser(i.e., as root or using sudo ). In some cases it may leave your system unusable by breaking system python.
Like in your answer math module exists and for numby the traceback didnt appear and for echo $? output was 0, Does it mean numpy is also present in my system?
In case you don’t have the module numpy how will you import it? When we do the coding we call the import statement by from numpy import *, will it install the module ? If not how will we install a new module?
It will be a septate question how to install a module. Need different packages for different module. For example to install vpython you need to install it as sudo apt-get install python-visual libgtkglextmm-x11-1.2-dev
don’t use sudo pip ; it may break system python. Use apt-get to install packages for system python. You could use pip —user option or virtualenv to install Python packages for yourself.
In case we do not want to unwantedly import a module in question (which would happen in a try statement) we can make use of sys.modules to test modules that are installed and were imported before.
In the python shell issue:
Then test for installed modules:
>>> 'numpy' in sys.modules True >>> 'scipy' in sys.modules False
Note that only those modules that were imported before give True on this test, all other modules (even if installed) result in False.
Another alternative to try an import statement in the python console is calling the inbuilt help() function. This will not give a documentation for non-installed modules, e.g.
>>> help('scipy') no Python documentation found for 'scipy'
The output of very long help documents of installed modules can be interrupted with Q .
Now to install missing modules it is recommended to use the Ubuntu package management (and not the Python pip way) because we need root access and also to prevent messing up our heavily Python-dependend system. For the module in question this would e.g. be:
sudo apt-get install python-scipy ## for Python2 sudo apt-get install python3-scipy ## for Python3
After installation we then can add them to the sys.modules dictionary by importing them once.
How to check does a file imports from another file in Python
I want to to check which file uses another file, just like tree command, just a folder name is enough so i tried an old method but it was inefficient ,dirty and that was not something that i expect. The method was i created a file in src named check.py , i imported all packages
from app.db import database from app.models import model_a, model_b from app.tests import test_x, test_y from app import main print('__file__= | __name__= | __package__='.format(__file__,__name__,str(__package__)))
print('__file__= | __name__= | __package__='.format(__file__,__name__,str(__package__)))
__file__=/home/yagiz/Desktop/struct/src/app/main.py | __name__=app.main | __package__=app __file__=/home/yagiz/Desktop/struct/src/app/db/database.py | __name__=app.db.database | __package__=app.db __file__=/home/yagiz/Desktop/struct/src/app/models/model_a.py | __name__=app.models.model_a | __package__=app.models __file__=/home/yagiz/Desktop/struct/src/app/models/model_b.py | __name__=app.models.model_b | __package__=app.models __file__=/home/yagiz/Desktop/struct/src/app/tests/test_x.py | __name__=app.tests.test_x | __package__=app.tests __file__=/home/yagiz/Desktop/struct/src/app/tests/test_y.py | __name__=app.tests.test_y | __package__=app.tests __file__=/home/yagiz/Desktop/struct/src/check.py | __name__=__main__ | __package__=None
The result is dirty and doesn’t meet my expectations is there a way to get a output like this?
main.py = app/models/model_a, app/models/model_b # These files imports something from main.py models_b = None # No file imports from models_b
Update, i tried @Hessam Korki’s suggestion it doesn’t works.
I looked up the source code of modulefinder and i found it adds a badmodule in every import statement which is not useful for me. Here is how did it go, first i created a function, also i created an another project structure.
src ├── empty.py ├── __init__.py ├── main.py ├── module_finder.py ├── other │ └── other.py ├── test │ └── some_app.py └── this_imports.py
from modulefinder import ModuleFinder file_names = ["this_imports.py", "main.py", "test/some_app.py", "other/other.py", "empty.py"] def check_imports(file_names): finder = ModuleFinder() for file in file_names: finder.run_script(file) print("\n", file) for name, mod in finder.modules.items(): print('%s: ' % name, end='') print(','.join(list(mod.globalnames.keys())[:3])) print('\n'.join(finder.badmodules.keys()))
from src.main import Test from src.test import DifferentTest
from src.main import Test class DifferentTest: pass
empty.py = None main.py = None other/other.py = src.main , src.test test/some_app.py = src.main this_imports.py = src.main
Filename: this_imports.py __main__: Test src.main Filename: main.py __main__: Test,__module__,__qualname__ src.main Filename: test/some_app.py __main__: Test,__module__,__qualname__ src.main Filename: other/other.py __main__: Test,__module__,__qualname__ src.main src.test Filename: empty.py __main__: Test,__module__,__qualname__ src.main src.test
How to check if a module is imported
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?
2 Answers 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')
Thanks, If for example I only import one specific functionality I doe snot work. For example I import watershed from skimage as: from skimage.morphology import watershed then doing: ‘watershed’ in sys.modules returns false. Is there a fix to this situation too?
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]