Neat Trick for Loading Modules with unknown Name

Peter Hansen peter at engcorp.com
Mon Mar 22 07:36:30 EST 2004


Brian Quinlan wrote:

>>I've found an easy and clean way to load and use modules that are loaded
>>after a program has started when the name of the module can not be
>>pre-determined.
>>
>>modname = 'usermodname'
>># load the module
>>exec('import ' + modname)
>># alias the module
>>usersmod = eval(modname)
> 
> 
> Do you really think that is easier than:
> 
> usersmod = __import__(modname)

__import__ doesn't handle packages, right?  The above with exec()
appears, unfortunately, to be the simplest approach(*) to handling 
*arbitrary* imports, even if they are nested as in xml.sax.whatever.

* The simplest, provided you're doing it once.  Otherwise, of course,
you would just write a function to do the job, and reuse that instead.
Then the dangers of the exec() approach are bypassed.

-Peter



More information about the Python-list mailing list