[Tutor] eval use (directly by interpreter vs with in a script)

Alan Gauld alan.gauld at btinternet.com
Mon Nov 3 19:04:09 CET 2014

On 03/11/14 17:33, Albert-Jan Roskam wrote:

> I sometimes do something like
> ifelse = "'teddybear' if bmi > 30 else 'skinny'"
> weightcats = [eval(ifelse) for bmi in bmis]
> Would this also be a *bad* use of eval? It can be avoided, but this is so concise.

eval etc are worst where the code to be evaluated is
coming from outside your program (eg a file, user
input etc)

So in your use case its not quite so dangerous since
the code is hard coded into your program. But its is still easily 
avoided by putting the ifelse bit into a function

def getWeight(bmi):
     return  'teddybear' if bmi > 30 else 'skinny'

weightcats = [getWeight(bmi) for bmi in bmis]

You could use the expression directly in the comprehension but I'm 
assuming the real examples are more complex...

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list