Python: How to pass arguments to the __code__ of a function?

Turion picture Turion · May 3, 2011 · Viewed 11k times · Source

The following works:

def spam():
    print "spam"
exec(spam.__code__)

spam

But what if spam takes arguments?

def spam(eggs):
    print "spam and", eggs
exec(spam.__code__)

TypeError: spam() takes exactly 1 argument (0 given)

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?

Edit: Since most readers tend not to believe in the usefulness of this, see the following use case:

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__ 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.

Another usecase:

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.

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.

Answer

Gustav Larsson picture Gustav Larsson · May 3, 2011

I am completely against this use of __code__.

Although I am a curious person, and this is what someone theoretically could do:

code # This is your code object that you want to execute

def new_func(eggs): pass
new_func.__code__ = code
new_func('eggs')

Again, I never want to see this used, ever. You might want to look into __import__ if you want to load code during run-time.