1

Is there any chance to use the snippets given below? When I run this code, it returns "module pandas is not installed"

a = "pandas"

try:
    import a
    print("module ",a," is installed")
except ModuleNotFoundError:
    print("module ",a," is not installed")

But when I run the code given below:

try:
    import pandas
    print("module pandas is installed")
except ModuleNotFoundError:
    print("module pandas is not installed")

It returns "module pandas is installed".

What is the difference between them?

Jaz
  • 53
  • 9
Melih
  • 13
  • 1
  • 5

4 Answers4

1

In the first example, what you're doing is more equivalent to the following:

try:
    import "pandas"
    print("module ",a," is installed")
except ModuleNotFoundError:
    print("module ",a," is not installed")

You can't import a string, unless you use importlib. You can find documentation for that library here. That would look something like the following:

import importlib

a = "pandas"

try:
    globals()[a] = importlib.import_module(a)
    print("module ",a," is installed")
except:
    print("module ",a," is not installed")
Jaz
  • 53
  • 9
0

You have to execute the script as one combined formatted string, using exec(), this actually executes the script:

a = "pandas"

try:
    exec(f'import {a}')
    print("module ",a," is installed")
except ModuleNotFoundError:
    print("module ",a," is not installed")

To read more about the Python exec() function, visit:

https://www.w3schools.com/python/ref_func_exec.asp

topsoftwarepro
  • 773
  • 5
  • 19
0

In your first example, you import a module named a (you cannot use variables in an import statement), which results in ModuleNotFoundError. In your second example, you import a module named pandas.

If you want to dynamically import a module (e.g. based on user input), use importlib:

import importlib

name = 'pandas'
try:
    module = importlib.import_module(name)
    print(f'Module {name} is installed')
except ModuleNotFoundError:
    print(f'Module {name} is not installed')

Do not use eval or exec - they are not safe.

W. Zhu
  • 755
  • 6
  • 16
0

@Jaz has successfully shown what is wrong with your first approach. You can't import a module by variable name using the import statement.

In general, python philosophy is to ask for forgiveness, not permission. So you often see the following construction in common modules that have optional dependencies:

try:
    import pandas
except ImportError:
    print("pandas is not installed")
else:
    print("pandas is installed")

The programmatic interface to the import statement is the built-in __import__ function. You can use it something like this:

m = 'pandas'
try:
    locals()[m] = __import__(m)
except ImportError:
    ...

A simplified interface is available in the functions of importlib.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264