newbie question - object from a string?

Gordon Scott gordon.scott at peregrine.com
Tue Nov 27 16:55:52 EST 2001


Thanks that did the trick!

-----Original Message-----
From: Fernando Pérez [mailto:fperez528 at yahoo.com]
Sent: Monday, November 26, 2001 3:59 AM
To: python-list at python.org
Subject: RE: newbie question - object from a string?


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
-- 
http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list