title: How to pass arguments to the __code__ of a function?
body: <p>The following works:</p>
  
  <pre><code>def spam():
      print "spam"
  exec(spam.__code__)
  </code></pre>
  
  <blockquote>
    <p>spam</p>
  </blockquote>
  
  <p>But what if <code>spam</code> takes arguments?</p>
  
  <pre><code>def spam(eggs):
      print "spam and", eggs
  exec(spam.__code__)
  </code></pre>
  
  <blockquote>
    <p>TypeError: spam() takes exactly 1 argument (0 given)</p>
  </blockquote>
  
  <p>Given, that I don't have access to the function itself but only to a code object, how can I pass arguments to the code object when executing it? Is it possible with eval?</p>
  
  <p>Edit: Since most readers tend not to believe in the usefulness of this, see the following use case:</p>
  
  <p>I want to save small Python functions to a file so that they can be called e.g. from another computer. (Needless to say here that this usecase restricts the possible functions severely.) Pickling the function object itself can't work because this only saves the name and the module where the function is defined. Instead, I could pickle the <code>__code__</code> of the function. When I unpickle it again, of course the reference to the function vanished, which is why I can't call the function. I simply don't have it at runtime.</p>
  
  <p>Another usecase:</p>
  
  <p>I work on several functions in one file that calculate some data and store it on the hard drive. The calculations consume a lot of time so I don't want to execute the functions every time, but only when the implementation of the function changed.</p>
  
  <p>I have a version of this running for a whole module instead of a function. It works by looking at the modification time of the file where the module is implemented in. But this is not an option if I have many functions that I don't want to separate in single files.</p>