Possible to import a module whose name is contained in a variable?

Michael Hoffman cam.ac.uk at mh391.invalid
Mon Mar 7 09:39:03 EST 2005


Ed Leafe wrote:
> 
>     Is there any way to use __import__ to replace the following:
> 
> exec("from %s import *" % modulename)

I shouldn't do this but:

module = __import__(modulename)
try:
     for key in module.__all__:
         globals()[key] = module[key]
except AttributeError:
     globals().update(module.__dict__)

But really, you shouldn't be using from x import * as it
has unpredictable results as well.

http://www.python.org/doc/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-module
-- 
Michael Hoffman



More information about the Python-list mailing list