<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Wed, Nov 27, 2013 at 12:09 PM, Ned Batchelder <span dir="ltr"><<a href="mailto:ned@nedbatchelder.com" target="_blank">ned@nedbatchelder.com</a>></span> wrote:<br>

<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="im"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
* Is there perhaps a better way to achieve what I'm trying to do?<br>

<br>
What I'm really after, is to check that python expressions embedded in text files are:<br>
- well behaved (no syntax errors etc)<br>
- don't accidentally access anything it shouldn't<br>
- I serve them with the values they need on execution<br>
</blockquote>
<br></div>
I hope you aren't trying to prevent malice this way: you cannot examine a piece of Python code to prove that it's safe to execute.  For an extreme example, see: Eval Really Is Dangerous: <a href="http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html" target="_blank">http://nedbatchelder.com/blog/<u></u>201206/eval_really_is_<u></u>dangerous.html</a><br>


<br>
In your environment it looks like you have a whitelist of identifiers, so you're probably ok.</blockquote></div><br>I just tested the crash example from that link in Python 2.7.5 win64 and the co_names from the compiled code is empty. Therefore, a simple whitelist would not catch that problematic code (and likely any other global access done correctly). Even a simple test of making sure that at least one (or any number of) valid identifier exists would be insufficent, as you can merely tack on a ",a" to add "a" to the co_names, and thus for any other variable.</div>

<div class="gmail_extra"><br></div><div class="gmail_extra">Basically, even with a pure whitelist, there is likely no possible way to make eval/exec safe, unless you also eliminate the ability to make literals.</div><div class="gmail_extra">

<br clear="all"><div>Chris</div>
</div></div>