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

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

    My method, I thing it`s more beautiful

    def f(x):
        print(x, x+1)
    
    g = type(f)(f.__code__, globals(), "optional_name")
    
    g(3)
    

提交回复
热议问题