2018-06-03から1日間の記事一覧

PythonでASTを逆変換してソースコードにする その2

whileループを抜き出して別の関数に埋め込む例 import ast import codegen expr=""" def main(): i = 0 while(i<3): print(i) i += 1 print("done") if __name__=="__main__": main() """ p=ast.parse(expr) while_part = p.body[0].body.pop(1) p1 = ast.pa…

PythonでASTを逆変換してソースコードにする

https://stackoverflow.com/a/769202 import ast import codegen expr=""" def foo(): print("hello world") """ p=ast.parse(expr) p.body[0].body = [ ast.parse("return 42").body[0] ] # Replace function body with "return 42" print(codegen.to_sourc…