dynamically load from module import xxx

Guilherme Polo ggpolo at gmail.com
Tue Jul 1 12:39:10 EDT 2008


On Tue, Jul 1, 2008 at 12:55 PM, Neal Becker <ndbecker2 at gmail.com> wrote:
> 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]})
>

You could change that line to: globals()[e] = getattr(module, e)

>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
-- Guilherme H. Polo Goncalves



More information about the Python-list mailing list