title: Modifying Python 3 code using abstract syntax trees
body: <p>I'm currently playing around with abstract syntax trees, using the ast and astor modules. The documentation taught me how to retrieve and pretty-print source code for various functions, and various examples on the web show how to modify parts of the code by replacing the contents of one line with another or changing all occurrences of + to *.</p>
  
  <p>However, I would like to <strong>insert</strong> additional code in various places, specifically when a function calls another function. For instance, the following hypothetical function:</p>
  
  <pre><code>def some_function(param):
      if param == 0:
         return case_0(param)
      elif param &lt; 0:
         return negative_case(param)
      return all_other_cases(param)
  </code></pre>
  
  <p>would yield (once we've used <code>astor.to_source(modified_ast)</code>):</p>
  
  <pre><code>def some_function(param):
      if param == 0:
         print ("Hey, we're calling case_0")
         return case_0(param)
      elif param &lt; 0:
         print ("Hey, we're calling negative_case")
         return negative_case(param)
      print ("Seems we're in the general case, calling all_other_cases")
      return all_other_cases(param)
  </code></pre>
  
  <p>Is this possible with abstract syntax trees? (note: I'm aware that decorating functions that are called would produce the same results when running the code, but this is not what I'm after; I need to actually output the modified code, and insert more complicated things than print statements).</p>