How to import a module based on an argument

Josiah Carlson jcarlson at
Fri Mar 26 23:35:59 CET 2004

> import inspect
> def functionname( modname ):
> 	exec("import "+modname)
> 	s = inspect.getsource( modname )
> 	return s
> How do I cast modname as a module name and not as a string?

Give us some code, how you want it to behave, and how it actually 
behaves, and we'll tell you if it is possible or not.  In general, what 
you are asking for does not seem possible.  Strings are strings.  Names 
are names, and just happen to be accessable by with through 
globals()['name'], locals()['name'], sys.modules['name'], etc.

If you have a string, and you want to get to a previously imported 
module, use:

 >>> import sys
 >>> module = sys.modules['os']
 >>> module
<module 'os' from 'f:\apps\python23\lib\os.pyc'>

If you need to import the module (because it hasn't been yet), as 
already mentioned:

 >>> module = __import__('os')
 >>> module
<module 'os' from 'f:\apps\python23\lib\os.pyc'>

In general, stay away from exec(), eval(), etc.  They are a security 
hole waiting to happen:


  - Josiah

More information about the Python-list mailing list