[Tutor] conditional import

David Porter jcm@bigskytel.com
Wed, 7 Mar 2001 21:53:50 -0700


* Jörg Wölke <lumbricus@gmx.net>:

> is there a way to import a module conditionally.

Yes. Use exception handling with a try statement:

try:
    import modul
except ImportError:
    pass


This way, if the module cannot be found (i.e., an ImportError), no exception
is raised.    

> I have (roughly) something like this:
> 
> def print_dict(modul):
> 	import modul           # here comes the error: no module
> 	print modul.__dict__   # named modul 
> 
> def main():
> 	mod=raw_input("Enter module name\n> ")
> 	print_dict(mod)
> 
> ###########################
> of course theres no module named modul but 
> shouldn't it replace modul with the result from
> raw_input() ????

No. import is literally searching for a module named modul in the search
paths. It is not looking for a variable in Python. E.G.,

>>> sys = 'donuts'
>>> print sys
donuts
>>> import sys 
>>> print sys
<module 'sys' (built-in)>


You would have to use something like exec to accomplish what you want:

modul = 'rfc822'
exec 'import '+modul


HTH,
David