How to pass arguments to the __code__ of a function? How to pass arguments to the __code__ of a function? python python

How to pass arguments to the __code__ of a function?


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 executedef new_func(eggs): passnew_func.__code__ = codenew_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.


Can you change the function to not take any arguments? The variables is then looked up from the locals/globals where you can supply into exec:

>>> def spam():...   print "spam and", eggs... >>> exec(spam.__code__, {'eggs':'pasta'})spam and pasta

(Why not just send the whole function as a string? Pickle "def spam(eggs): print 'spam and', eggs", and exec the string (after verification) on the other side.)


I think there are probably some design considerations in your larger application that could make you not care about this problem, like perhaps having some collection of 'known good and valid' functions distributed as a module that the executing agents know about or something.

That said, one hacky solution would be:

>>> def spam(eggs):...     print "spam and %s" % eggs...     ... >>> spam('bacon')spam and bacon>>> def util():...     pass...     ... >>> util.__code__ = spam.__code__>>> util('bacon')spam and bacon>>>