eval vs. exec

Andrei Kulakov ak at silmarill.org
Wed May 29 23:46:29 EDT 2002


In article <yfsadql4r2n.fsf at black132.ex.ac.uk>, Alexander Schmolck wrote:
> Simon Budig <Simon.Budig at unix-ag.org> writes:
> 
>> Hi.
>> 
>> I currently have problems to let code inside strings execute as I want
>> to have it. Especially the difference between "eval" and "exec"
>> (resp. compiling as 'eval' or as 'single') makes me headache.
>> I want to execute things like the three following strings:
>> 
>> "a = 2"           ---> returns nothing
>> "3 * 4"           ---> returns 12
>> "a=2; b=3; a*b"   ---> returns 6
> 
> 
> The distiction is quite simple: use eval for expressions and exec for
> everything else. That of course only works if you know what qualifies as an
> expression in python :)
> 
> Maybe this helps: an expression is something that returns a value, so anything
> you can write on the right side of an '=' is an expression (unless it already
> has an "=" in it) and everything you can't isn't. So only example 2 above is
> an expression. If you have an expression, use eval, else use exec, which will
> execute arbitrary code in the dictionary you specify with "in" (default
> globals, but I'd never use that).
>
Thanks!  I knew the difference between expressions and
statements but I'd always forget it. Now I'll remember it goes on
the right side of an equal sign. The simplest explanation is
often the best and most memorable :-).

 - Andrei

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



More information about the Python-list mailing list