Newbie question about evaluating raw_input() responses

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu May 23 00:47:45 EDT 2013


On Wed, 22 May 2013 22:31:04 +0000, Alister wrote:

> Please write out 1000 time (without using any form of loop)
> 
> "NEVER use input in python <3.0 it is EVIL"*
> 
> as Chris A point out it executes user input an can cause major damage
> (reformatting the hard disk is not impossible!)

Is he allowed to use eval instead of a loop?

print (eval("NEVER use input in python <3.0 it is EVIL\n"*1000))

*wink*


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! 

(I just wish that eval and exec where in a module, rather than built-in, 
to help discourage casual usage by beginners who don't know what they're 
doing.)

For example, collections.namedtuple uses eval to dynamically generate new 
classes on the fly from arguments given. But it is safe to use, because 
it has been designed by experts to be safe and tested in great detail.

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 :-)



-- 
Steven



More information about the Python-list mailing list