dynamically load from module import xxx

Neal Becker ndbecker2 at gmail.com
Tue Jul 1 17:55:34 CEST 2008


Guilherme Polo wrote:

> On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker <ndbecker2 at gmail.com> wrote:
>> What is a good way to emulate:
>>
>> from module import xxx
>> where 'module' is a dynamically generated string?
>>
>> __import__ ('modulename', fromlist=['xxx'])
>>
>> seems to be what I want, but then it seems 'xxx' is not placed in
>> globals() (which makes me wonder, what exactly did fromlist do?)
> 
> fromlist is used for importing subpackages/submodules of the first arg
> of __import__. Since you are using "modulename", I'm guessing it is
> not a package, fromlist will do nothing for you.
> To solve your problem you could do getattr(__import__('modulename'),
> 'xxx').

This seems to be what I want, don't know if there is a simpler way:

stuff =['A','B'] 
module = __import__ (modulename)
for e in stuff:
  globals().update({e :  module.__dict__[e]})






More information about the Python-list mailing list