<html>
  <head>
    <meta content="text/html; charset=ISO-8859-1"
      http-equiv="Content-Type">
  </head>
  <body text="#000000" bgcolor="#FFFFFF">
    <div class="moz-cite-prefix">On 1/4/2013 5:33 AM, Steven D'Aprano
      wrote:<br>
    </div>
    <blockquote
      cite="mid:50e6da35$0$30003$c3e8da3$5496439d@news.astraweb.com"
      type="cite">
      <pre wrap="">On Fri, 04 Jan 2013 07:24:04 -0500, Terry Reedy wrote:

</pre>
      <blockquote type="cite">
        <pre wrap="">On 1/3/2013 6:25 PM, Grant Edwards wrote:
</pre>
        <blockquote type="cite">
          <pre wrap="">
I've written a small assembler in Python 2.[67], and it needs to
evaluate integer-valued arithmetic expressions in the context of a
symbol table that defines integer values for a set of names.  The
"right" thing is probably an expression parser/evaluator using ast, but
it looked like that would take more code that the rest of the assembler
combined, and I've got other higher-priority tasks to get back to.
</pre>
        </blockquote>
        <pre wrap="">
Will ast.literal_eval do what you want?
</pre>
      </blockquote>
      <pre wrap="">
No. Grant needs to support variables, not just literal constants, hence 
the symbol table.


</pre>
    </blockquote>
    Apologies for the delayed response...<br>
    <br>
    Seems like it would be a bit safer and easier to approach this
    problem by stretching the capability of ast.literal_eval() rather
    than attempting to sandbox eval().<br>
    <br>
    How about ast.literal_eval after performing lexical substitution
    using the symbol table?<br>
    <br>
    Assignment into the symbol table, and error handling, are exercises
    left to the reader. <br>
    <br>
    Something vaguely like this:<br>
    <blockquote><i>pseudocode:</i><br>
      <br>
      <tt>def safe_eval(s, symbols={}):</tt><br>
      <tt>    while search(s, r'\w+')</tt><tt>:</tt><br>
      <tt>        replace match with '('+repr(symbols[match])</tt><tt>+')'
        in s</tt><br>
      <tt>    return ast.literal_eval(s)</tt><br>
      <br>
    </blockquote>
    - Ken<br>
    <br>
  </body>
</html>