title: How do you do a python 'eval' only within an object context?
body: <p>Is it possible to do something like</p>
  
  <pre><code>c = MyObj()
  c.eval("func1(42)+func2(24)")
  </code></pre>
  
  <p>in Python..i.e. have func1() and func2() be evaluated within the scope of the object 'c' (if they were member functions within that class definition)? I can't do a simple parsing, since for my application the eval strings can become arbitrarily complicated. I guess doing some magic with the ast module might do the trick, but due to the dirth of literature on ast, I'm not sure where to look:</p>
  
  <pre><code>import ast
  
  class MyTransformer(ast.NodeTransformer):
      def visit_Name(self, node):
          # do a generic_visit so that child nodes are processed
          ast.NodeVisitor.generic_visit(self, node)
          return ast.copy_location(
              # do something magical with names that are functions, so that they become 
              # method calls to a Formula object
              newnode,
              node
          )
  
  class Formula(object):
  
      def LEFT(self, s, n):
          return s[:n]
  
      def RIGHT(self, s, n):
          return s[0-n:]
  
      def CONCAT(self, *args, **kwargs):
          return ''.join([arg for arg in args])
  
  def main():
  
      evalString = "CONCAT(LEFT('Hello', 2), RIGHT('World', 3))"
  
      # we want to emulate something like Formula().eval(evalString)
      node = ast.parse(evalString, mode='eval')
      MyTransformer().visit(node)
  
      ast.fix_missing_locations(node)
      print eval(compile(node, '&lt;string&gt;', mode='eval'))    
  </code></pre>