a question from a newcomer to this language

Michael Chermside mcherm at mcherm.com
Fri Jun 10 15:49:46 EDT 2005


Shankar writes:
> Is there any way to convert a string into an instruction that will be
> executed?

Short answer:
    Yes. The exec statement does what you want:

>>> x = 3
>>> y = 4
>>> exec "z = x * y"
>>> print z
12

HOWEVER... the long answer is that you almost certainly do NOT want
to use exec. Nearly everything that can be done with exec can be
done without it and the solution that does NOT use exec is faster,
more understandable, and has better security features. Often the
solution that does not use exec will be simpleer and more elegant
as well.

If you look at a problem and are nearly certain that it needs to be
solved using exec, try posting it here... the people on this newsgroup
are very good at solving challenges like that. But try it yourself
first... you may learn something.

-- Michael Chermside




More information about the Python-list mailing list