<br><br><div class="gmail_quote">On Mon Nov 03 2014 at 10:04:41 AM Alan Gauld <<a href="mailto:alan.gauld@btinternet.com">alan.gauld@btinternet.com</a>> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">On 03/11/14 17:33, Albert-Jan Roskam wrote:<br>
<br>
> I sometimes do something like<br>
> ifelse = "'teddybear' if bmi > 30 else 'skinny'"<br>
> weightcats = [eval(ifelse) for bmi in bmis]<br>
><br>
> Would this also be a *bad* use of eval? It can be avoided, but this is so concise.<br>
<br></blockquote><div><br></div><div>Yes, this is bad and you need to learn to instinctively wince when you see this.  I know that I am.  :P</div><div><br></div><div>Even if you don't think about the security perspective, this is not good from an engineering perspective: eval() is a dynamic recompilation of that bit of source code every single time it goes through the loop.</div><div><br></div><div>The only thing that is "varying" here is bmi, and when we're writing a code that's parameterized by a varying value, the tool to use isn't eval(): you want to use a function.</div><div><br></div><div>Here's what this looks like:</div><div><br></div><div>#########################################</div><div>def ifelse(bmi): return 'teddybear' if bmi > 30 else 'skinny'</div><div>weightcats = [ifelse(bmi) for bmi in bmis]<br></div><div>#########################################</div><div><br></div><div>This is formatted deliberately to show that this is about the same length as the original code, but significantly safer and more performant.  Performant because Python isn't reparsing the code that computes the bmi label.</div><div><br></div><div>Safer because the behavior of the function-using code is much more statically definable: you can tell from just reading the source code that it can only do a few things: it either computes a value, or maybe it errors if bmi is not a number.  eval(), on the other hand, can be a big black hole of badness just waiting to happen.</div><div><br></div><div>Consider if 'bmi' were ever controlled from the outside world.  At the very worst, the normal function approach will raise a runtime error, but that's it.  In contrast, the eval approach can take over your machine.</div></div>