Reputation: 3100
I want to be able (just for fun and didactic purposes) to modify the AST of a function just to change a string that should be printed out.
Now after some experiments I thought that something like this should work, however even if there are no errors the second function never prints anything.
Any idea about what I'm missing? (The second function should just print 'world' instead of 'hello world' basically).
def function_hello():
print('hello world')
def remove_hello():
import ast
import inspect
source = inspect.getsource(function_hello)
ast_tree = ast.parse(source)
st = ast_tree.body[0].body[0].value.args[0]
st.s = st.s.replace('hello ', '')
return compile(ast_tree, __file__, mode='exec')
if __name__ == '__main__':
function_hello()
exec(remove_hello())
Upvotes: 4
Views: 893
Reputation: 369444
Executing the compiled code overwrites the function function_hello
(not calling it). You need to call function_hello()
to see what you want.
if __name__ == '__main__':
function_hello()
exec(remove_hello()) # This does not call the function.
function_hello() # <-----------
Upvotes: 4