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

前端 未结 6 465
别那么骄傲
别那么骄傲 2020-12-02 20:55

The following works:

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

spam

But what if spam

6条回答
  •  盖世英雄少女心
    2020-12-02 21:32

    I don't think you can pass arguments to either exec or eval, so that they are passed to the code object.

    You could resort to the string version of exec/eval, e.g. exec("spam(3)").

    You could create another code object that binds the argument, and then exec this:

    def spam_with_eggs():
       return spam(3)
    exec(spam_with_eggs.__code__)
    

    (I thought you could also achieve this with functools.partial, but didn't get it to work).

    EDIT:

    After reading your additional explanations I thought of ways to re-establish a proper function from the code object. This simple approach worked for me (in python2.5):

    def bar():pass
    bar.func_code = spam.func_code
    bar(3)  # yields "spam and 3"
    

提交回复
热议问题