Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AST manipulation in Python

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())
like image 532
andrea_crotti Avatar asked Oct 24 '25 00:10

andrea_crotti


1 Answers

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()  # <-----------
like image 138
falsetru Avatar answered Oct 25 '25 13:10

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!