Modify code with AST

Ronny Mandal ronnyma at volatile.no
Wed Jun 12 06:36:52 EDT 2013


> I think the main problem is that you have to return the unchanged node (you 
> 
> return None which might be an indentation accident). I also had to take the 
> 
> add() FunctionDef out of the enclosing Module. So (I don't have codegen or 
> 
> is it part of the stdlib?):

Thank you, my problem is now solved. It was the indentation of the return statement which was the culprit. I forgot that visit() (in this context) is called once for each FunctionDef-node. I moved the return-statement one click to the left, then it worked.

codegen is not a part of the stdlib. It is written by Armin Ronacher (the same person who wrote ast) and it uses ast to generate python code from the AST.

Thanks!


Regards,

Ronny Mandal

> 
> 
> 
> import ast
> 
> 
> 
> class FindAndTransform(ast.NodeTransformer):
> 
>     def visit_FunctionDef(self, node):
> 
>         if node.name == 'Foo':
> 
>             node = ast.parse('''
> 
> def add(n, m):
> 
>   return n + m
> 
> ''').body[0]
> 
>         return node
> 
> 
> 
> if __name__ == "__main__":
> 
>     orig = """
> 
> class FooBar():
> 
>   def Foo(self): #I want to replace this and only this
> 
>     return 1
> 
> 
> 
>   def Bar(self):
> 
>     return 2
> 
> """
> 
> 
> 
>     p = ast.parse(orig)
> 
>     q = FindAndTransform().visit(p)
> 
>     qq = compile(q, "<nofile>", "exec")
> 
>     exec(qq)
> 
>     assert {n for n in dir(FooBar) if not n.startswith("_")} == {"Bar", 
> 
> "add"}



More information about the Python-list mailing list