[Tutor] eval and exec

Alan Gauld alan.gauld at freenet.co.uk
Sat Dec 4 10:34:49 CET 2004

> I'm having trouble understanding the difference between eval and

eval evaluates an *expression* - that is something that returns a

exec executes a piece of code, it need not return a value.

eval is slightly safer than exec (but not much).

Some examples:

print 'hello'   # use exec for this

6+7-9/3    # use eval for this

myfunction(42)   # use eval for this

to make eval useful you need to assign the result to a variable:

res = eval('6+7-9/3')

but exec is just executed on its own:

exec('print "hello"')

Both are extremely dangerous functions from a security
and maintenance/reliability pouint of view and should be
used very rarely.

Was there anything more specific you wanted to know?


Alan G.

More information about the Tutor mailing list