newbie question - object from a string?

Fernando Pérez fperez528 at yahoo.com
Mon Nov 26 06:59:04 EST 2001


Gordon Scott wrote:

> Thanks for the reply.  Didn't get this until this morning.
> 
> I have a file named MyHandlers.py in which I have the class MyHandler.
> 
> when I use
> 
> __import__('MyHandlers', globals(), locals(), ['MyHandler'])  or
> .
> .
> .
> eval('MyHandler()', globals(), locals())  or eval('MyHandlers.MyHandler()',
> globals(), locals())
> 
> I get a NameError: name 'MyHandler' is not defined.

Python is dynamic. Just generate the code:

mod = 'MyHandlers'
cls = 'MyHandler'

exec 'from '+mod+' import '+cls

That should work just fine.

Cheers,

f



More information about the Python-list mailing list