title: replace variable names with actual values in an expression in AST python
body: <p>I have an expression described in variable forms like this</p>
  <pre><code>'s1*3 - (s2-s1)*1'
  </code></pre>
  <p>I have given values of s1 and s2 that can change according to the need</p>
  <p>I can use python <a href="https://docs.python.org/2/library/ast.html" rel="nofollow noreferrer">ast</a> module to evaluate this expression by replacing the respective s1 and s2 values (s1 = 20,s2=30)</p>
  <pre><code>import ast
  import operator as op
  
  operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
               ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
               ast.USub: op.neg}
  
  def eval_(node):
      if isinstance(node, ast.Num): # &lt;number&gt;
          return node.n
      elif isinstance(node, ast.BinOp): # &lt;left&gt; &lt;operator&gt; &lt;right&gt;
          return operators[type(node.op)](eval_(node.left), eval_(node.right))
      elif isinstance(node, ast.UnaryOp): # &lt;operator&gt; &lt;operand&gt; e.g., -1
          return operators[type(node.op)](eval_(node.operand))
      else:
      raise TypeError(node)
  
  &gt;&gt;&gt; str1 = '20*3 - (30-20)*1'
  &gt;&gt;&gt; node = ast.parse(str1, mode='eval')
  &gt;&gt;&gt; eval_(node.body)
  50
  </code></pre>
  <p>How should I evaluate this expression without the need to replace the variables with their actual values.</p>
  <p>Thanks</p>