Newbie question about evaluating raw_input() responses

Chris Angelico rosuav at gmail.com
Thu May 23 02:04:09 EDT 2013


On Thu, May 23, 2013 at 2:47 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> But all joking aside, eval is dangerous, yes, but it is not "evil". It
> needs to be handled with caution, but there are good uses for it. In
> fact, there are a few -- a very few -- things which can *only* be done
> with eval or exec. That's why it is part of the language!
>...
>
> So while it is right and proper to treat eval with great respect as a
> powerful (and therefore dangerous) tool, and avoid it whenever you don't
> *need* it, there is no reason to be irrational about it :-)

No need to be irrational about eval(), but I do agree that input()
should never be used. Especially now that Py3 has changed the meaning
of input(), it's potentially very confusing to call the old function;
be explicit and use eval(raw_input()) if you actually want that.

Quite apart from the extreme danger of eval'ing something tainted
(which isn't a problem if you KNOW the user's trusted - eg if you're
effectively writing an interactive interpreter for yourself), input()
is just too concealing; it's not obvious that code will be executed.

Above all, I don't want to see people advised to eval things as a
solution to simple problems. Maybe it's safe *right now*, but any
advice that solves today's problem will be used to solve tomorrow's
problem too, and tomorrow's problem will involve code going to someone
untrusted who suddenly gets full code execution.

But this is why we have a mailing list, not one-on-one advice. Kevin's
post is bound to get a follow-up, just as my posts are when I say
something incorrect. It gives that measure of extra confidence:
"Correct me if I'm wrong, but..." is implicitly prefixed to everything
:)

So Kevin, please don't get me wrong: I'm not hating on you, I'm not
wishing you hadn't posted. But I *will* speak strongly against the Py2
input() function. :)

Chris Angelico



More information about the Python-list mailing list