The following works:
def spam():
print \"spam\"
exec(spam.__code__)
spam
But what if spam
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
.)