eval vs. exec

Simon Budig Simon.Budig at unix-ag.org
Mon May 27 15:41:30 EDT 2002


Alexander Schmolck <a.schmolck at gmx.net> wrote:
> Simon Budig <Simon.Budig at unix-ag.org> writes:
>> Alexander Schmolck <a.schmolck at gmx.net> wrote:
>> > Simon Budig <Simon.Budig at unix-ag.org> writes:
> 
> Sorry, I didn't mean to state the obvious, but it seems to be confusing to
> many people, especially since assignments can form part of expressions in
> many languages.

Well, originally this was confusing to me. I now know this fact but
sometimes would love to be able to do something like

   if (match = re.match ("spam", eggs)):
      print match.group (0)

similiarily: Why does "a = b = 2" work, but making the associativity
explicit ("a = (b = 2)") does not?

But I'd guess this is kind of a holy cow I'd better avoid to touch...  :-)

> Well, if all your stuff is exclusively math expressions which can only
[...]

> Anyway, this all seems to be heading down the wrong track. I'm not completely
> clear I understand your problem, but is my assumption right that it basically
> is:
> 
>   "I have string consisting of a series of assignment statements (possibly 0)
>   followed by an expression and I want to return the value of this
>   expression?" ?
 
Sorry, my fault. Maybe I should have phrased this question better.
I try to be a bit more general.

The specific problem of math expressions is not the main problem here.
I am just astonished about the uglyness of eval/exec'ing code.
Why is it not as simple as:

>>> print repr (eval ("3*4"))
12
>>> print repr (eval ("a=2"))
None

Why is there this distinction between 'single' and 'eval'?

The interactive console is able to handle "3*4" as well as "a=2" without
having to specify the type of input, why not eval?

eval could - for example - return a list of collected return values:
eval ("[1,2,3] * 2 ; 3*4 ; 7*8 ; a=2")  --->  [[1,2,3,1,2,3], 12, 56]

> However, all the tricks you have to play to make this stuff safe are
> presumably more of an effort than parsing it properly, especially since
> parsing simple math expressions often comes as example code for parser
> generators and is such a common problem that it shouldn't be that hard to
> find something canned.

This is - as always - a tradeoff thingie. I don't see a good reason
to implement something that has been solved better - and more general -
in python itself again. It is not a permanent service, it is not used
for mission critical stuff, and the people that are able to put stuff
from the external python into this environment without having references
to it probably won't bother. Maybe this is too optimistic, but It is
good enough for me. Currently the eval/exec thing is more interesting
to me  :-)
 
Thanks,
        Simon

-- 
      Simon.Budig at unix-ag.org       http://www.home.unix-ag.org/simon/



More information about the Python-list mailing list