[Tutor] loading modules dynamically
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Mon, 10 Sep 2001 15:37:22 -0700 (PDT)
On Mon, 10 Sep 2001, Girish Gajwani wrote:
> Hi all,
>
> I have been trying to load modules dynamically using the
> __import__ hook , as follows:
>
> #######################
> #! /usr/bin/env python
>
> def my_import(name):
> mod = __import__(name)
> print mod
> print dir(mod)
> return mod
>
> mod = my_import("os")
> print mod.listdir(".")
> #######################
>
> My interpretation of the __import__ hook is that it loads
> the module mentioned & also, aliases it to mod. Is this
> correct? I could not understand the documentation mentioned
> in the library reference wrt __import__, hence this
> question.
Yes, __import__ does load the module and return it:
###
>>> m = __import__('os')
>>> m
<module 'os' from '/home/dyoo/local/lib/python2.1/os.pyc'>
###
Note, though, that importing modules this way doesn't automatically allow
us to reference the os module with the name 'os':
###
>>> os
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'os' is not defined
###
> Also, in what case can the above scene fail? What error
> checking would I need to add here?
When Python imports a module, and runs into an error, it will raise an
"ImportError". For example:
###
>>> m = __import__('skljfflskj')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: No module named skljfflskj
###
What we can do is write a small exception handler that checks for this
situation. Here's one version of my_import() that checks for
ImportErrors:
def my_import(name):
try:
mod = __import__(name)
except ImportError:
print "Whoops, I don't know about", name
return None
print mod
print dir(mod)
return mod
HOpe this helps!