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

前端 未结 6 448
别那么骄傲
别那么骄傲 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:33

    A code object is part of a function, so several answers above suggest creating a dummy function and replacing its __code__ with your codeObject. Here's another way that avoids making and throwing away a new __code__:

    import new
    newFunction = new.function(codeObject, globals())
    

    (Tested in Python 2.7, where spam.__code__ is named spam.func_code.)

提交回复
热议问题