title: Modify function in decorator
body: <p>I was thinking about making a decorator for the purpose of increasing performance. A decorator that modifies the source code of the function it decorates, and returns the modified function.</p>
  
  <p>While thinking this through, I figured that if I could just get the source code of the function, I could do this. But is it possible to access the source code of a function inside a decorator? If I have a decorator like this:</p>
  
  <pre><code>import inspect
  
  def decorate(f):
      exec(inspect.getsource(f))
      return eval(f.__name__)
  
  @decorate
  def test():
      return 1
  </code></pre>
  
  <p>I get an OSError:</p>
  
  <pre><code>OSError: could not get source code
  </code></pre>
  
  <p>This appears to be because <code>test</code> is not fully formed before it is passed into <code>decorate</code>. However, this works:</p>
  
  <pre><code>import inspect
  
  def decorate(f):
      exec(inspect.getsource(f))
      return eval(f.__name__)
  
  def test():
      return 1
  test = decorate(test)
  </code></pre>
  
  <p>It just doesn't have that decorator flair to it, though. It seems that this might be possible, because <code>f.__code__</code> <em>is</em> defined.</p>
  
  <hr>
  
  <p>Upon further inspection, it appears that this only happens when I put the <code>inspect.getsource(f)</code> into <code>exec</code>. Otherwise, it seems that I can get the source code.</p>
  
  <hr>
  
  <p>As a rough sketch of the first thing that's on my mind, I'm thinking of tail-recursion. I wrote this decorator that is unfortunately slow and requires a very specific style of writing the function to be decorated:</p>
  
  <pre><code>def tail_recurse(acc_default):
      def decorate(f):
          def wrapper(*args, acc=acc_default):
              args = args + (acc,)
              while True:
                  return_type, *rargs = f(*args)
                  if return_type is None:
                      return rargs[-1]
                  args = rargs
          return wrapper
      return decorate
  </code></pre>
  
  <p>Basically, I'm thinking of doing something as simple as replacing the body of a function with:</p>
  
  <pre><code>while True:
      __body__
      update_args
  </code></pre>