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

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

    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.

提交回复
热议问题