eval vs. exec

Delaney, Timothy tdelaney at avaya.com
Mon May 27 20:15:29 EDT 2002


> From: Simon Budig [mailto:Simon.Budig at unix-ag.org]
> 
> 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'?

Assignment (binding) is not an expression in Python. This is a Good
Thing(TM).

> 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?

The interactive console is actually playing tricks. When it sees a plain
expression, it prints the result. This does not happen when you run a
script.

> 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

You are too optimistic. Never assume anything is not a permanent service -
everything will last longer than you intended, because people are afraid to
change things that currently work. In many cases, this fear is justified.

Any time you are using code from an untrusted source you need to be
incredibly careful. This includes third-party modules (I assume you trust
the implementors of Python and its standard libraries ...). A trusted
associate today may turn out to be a bitter ex-employee with a nasty
backdoor into your systems in the future.

If this is running on an isolated system, where you don't care if someone
(accidentally or otherwise) messes it up, then OK. Of course, it will need
to be a *real* isolated system - otherwise someone could write some
networking code, exec it, and compromise your network. Oops.

Tim Delaney





More information about the Python-list mailing list