Issue
I am trying to import modules from a list. This would be to allow easier editing of imported modules, cleaner error message, and better error handling. Here is basically what I am trying to do:
imports = ['sys', 'itertools', 'datetime', 'os']
for x in imports:
try:
import x
print "Successfully imported ", x, '.'
except ImportError:
print "Error importing ", x, '.'
The issue here is that it tries importing x, not the value x should hold. I realize that to import from the list I could do something like below, but I do not see a way to handle the errors with it:
imports = ['sys', 'itertools', 'datetime', 'os']
modules = map(__import__, imports)
Is there a way to integrate the error handling with this method or should I try a different approach?
Solution
Instead of mapping them to ___import__
all at once, just append each module to the list modules
one at a time inside the for-loop:
imports = ['sys', 'itertools', 'datetime', 'os']
modules = []
for x in imports:
try:
modules.append(__import__(x))
print "Successfully imported ", x, '.'
except ImportError:
print "Error importing ", x, '.'
Note however that most Python programmers prefer the use of importlib.import_module
rather than __import__
for this task.
Note too that it might be better to make modules
a dictionary instead of a list:
imports = ['sys', 'itertools', 'datetime', 'os']
modules = {}
for x in imports:
try:
modules[x] = __import__(x)
print "Successfully imported ", x, '.'
except ImportError:
print "Error importing ", x, '.'
Now, instead of by index:
modules[0].version
modules[3].path
you can access the modules by name:
modules["sys"].version
modules["os"].path
Answered By - user2555451 Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.