[Tutor] conditional import

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 8 Mar 2001 07:32:06 +0100


On Thu, Mar 08, 2001 at 04:53:12AM +0100, Jörg Wölke wrote:
> Hello!!!
> 
> is there a way to import a module conditionally.
> 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() ????
> what am i missing?

Import doesn't take variables, only the real name of a module.
For instance, it's 
   import string
instead of
   import "string"
   
You can use the __import__ function which imports and returns a module:

def print_dict(modulename):
   module = __import__(modulename)
   print module.__dict__
   
This loads any module by its name and calls it module locally.

-- 
Remco Gerlich