[Tutor] exec "self.abc=22" ?

Alan Gauld alan.gauld at btinternet.com
Mon Feb 16 21:11:28 CET 2009


"Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote 

> Python doesn't like the code in the Subject (unqualified exec 
> not allowed in function). but easily likes self.abc="22". 

We'd need to see the code and traceback to guess why...

> However, I'd like to assemble the assignment as a string, 
> as shown in Subject, and execute it. Is there a way to do this?

exec is the usual way but it's also usually a bad idea.

Any reason why you want to do that rather than any of 
the safer alternatives? (dict, setattr etc)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list