[Python] Parse a .py file, read the AST, modify it, then write back the modified source code
The builtin ast module doesn't seem to have a method to convert back to source. However, the codegen module here provides a pretty printer for the ast that would enable you do do so. eg.
import ast import codegen expr=""" def foo(): print("hello world") """ p=ast.parse(expr) p.body.body = [ ast.parse("return 42").body ] # Replace function body with "return 42" print(codegen.to_source(p))
This will print:
def foo(): return 42
Note that you may lose the exact formatting and comments, as these are not preserved.
However, you may not need to. If all you require is to execute the replaced AST, you can do so simply by calling compile() on the ast, and execing the resulting code object.
I want to programmatically edit python source code. Basically I want to read a
.py file, generate the AST, and then write back the modified python source code (i.e. another
There are ways to parse/compile python source code using standard python modules, such as
compiler. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.
UPDATE: The reason I want to do this is I'd like to write a Mutation testing library for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.
Parsing and modifying the code structure is certainly possible with the help of
ast module and I will show it in an example in a moment. However, writing back the modified source code is not possible with
ast module alone. There are other modules available for this job such as one here.
NOTE: Example below can be treated as an introductory tutorial on the usage of
ast module but a more comprehensive guide on using
ast module is available here at Green Tree snakes tutorial and official documentation on
>>> import ast >>> tree = ast.parse("print 'Hello Python!!'") >>> exec(compile(tree, filename="<ast>", mode="exec")) Hello Python!!
You can parse the python code (represented in string) by simply calling the API
ast.parse(). This returns the handle to Abstract Syntax Tree (AST) structure. Interestingly you can compile back this structure and execute it as shown above.
Another very useful API is
ast.dump() which dumps the whole AST in a string form. It can be used to inspect the tree structure and is very helpful in debugging. For example,
On Python 2.7:
>>> import ast >>> tree = ast.parse("print 'Hello Python!!'") >>> ast.dump(tree) "Module(body=[Print(dest=None, values=[Str(s='Hello Python!!')], nl=True)])"
On Python 3.5:
>>> import ast >>> tree = ast.parse("print ('Hello Python!!')") >>> ast.dump(tree) "Module(body=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Str(s='Hello Python!!')], keywords=))])"
Notice the difference in syntax for print statement in Python 2.7 vs. Python 3.5 and the difference in type of AST node in respective trees.
How to modify code using
Now, let's a have a look at an example of modification of python code by
ast module. The main tool for modifying AST structure is
ast.NodeTransformer class. Whenever one needs to modify the AST, he/she needs to subclass from it and write Node Transformation(s) accordingly.
For our example, let's try to write a simple utility which transforms the Python 2 , print statements to Python 3 function calls.
Print statement to Fun call converter utility: print2to3.py:
#!/usr/bin/env python ''' This utility converts the python (2.7) statements to Python 3 alike function calls before running the code. USAGE: python print2to3.py <filename> ''' import ast import sys class P2to3(ast.NodeTransformer): def visit_Print(self, node): new_node = ast.Expr(value=ast.Call(func=ast.Name(id='print', ctx=ast.Load()), args=node.values, keywords=, starargs=None, kwargs=None)) ast.copy_location(new_node, node) return new_node def main(filename=None): if not filename: return with open(filename, 'r') as fp: data = fp.readlines() data = ''.join(data) tree = ast.parse(data) print "Converting python 2 print statements to Python 3 function calls" print "-" * 35 P2to3().visit(tree) ast.fix_missing_locations(tree) # print ast.dump(tree) exec(compile(tree, filename="p23", mode="exec")) if __name__ == '__main__': if len(sys.argv) <=1: print ("\nUSAGE:\n\t print2to3.py <filename>") sys.exit(1) else: main(sys.argv)
This utility can be tried on small example file, such as one below, and it should work fine.
Test Input file : py2.py
class A(object): def __init__(self): pass def good(): print "I am good" main = good if __name__ == '__main__': print "I am in main" main()
Please note that above transformation is only for
ast tutorial purpose and in real case scenario one will have to look at all different scenarios such as
print " x is %s" % ("Hello Python").
In a different answer I suggested using the
astor package, but I have since found a more up-to-date AST un-parsing package called
>>> import ast >>> import astunparse >>> print(astunparse.unparse(ast.parse('def foo(x): return 2 * x'))) def foo(x): return (2 * x)
I have tested this on Python 3.5.
A Program Transformation System is a tool that parses source text, builds ASTs, allows you to modify them using source-to-source transformations ("if you see this pattern, replace it by that pattern"). Such tools are ideal for doing mutation of existing source codes, which are just "if you see this pattern, replace by a pattern variant".
Of course, you need a program transformation engine that can parse the language of interest to you, and still do the pattern-directed transformations. Our DMS Software Reengineering Toolkit is a system that can do that, and handles Python, and a variety of other languages.
See this SO answer for an example of a DMS-parsed AST for Python capturing comments accurately. DMS can make changes to the AST, and regenerate valid text, including the comments. You can ask it to prettyprint the AST, using its own formatting conventions (you can changes these), or do "fidelity printing", which uses the original line and column information to maximally preserve the original layout (some change in layout where new code is inserted is unavoidable).
To implement a "mutation" rule for Python with DMS, you could write the following:
rule mutate_addition(s:sum, p:product):sum->sum = " \s + \p " -> " \s - \p" if mutate_this_place(s);
This rule replace "+" with "-" in a syntactically correct way; it operates on the AST and thus won't touch strings or comments that happen to look right. The extra condition on "mutate_this_place" is to let you control how often this occurs; you don't want to mutate every place in the program.
You'd obviously want a bunch more rules like this that detect various code structures, and replace them by the mutated versions. DMS is happy to apply a set of rules. The mutated AST is then prettyprinted.