NodeTransformer: how to remove nodes?

Peter Otten __peter__ at web.de
Mon Aug 19 07:21:51 EDT 2013


Tobias Müller wrote:

> I'm facing an issue with NodeTransformer, a tool used for Python AST
> manipulations.
> 
> Last week I posted on stackoverflow.com, but there are no responses yet.
> Maybe someone reading the mailing list can have a look and leave me a
> response here or over there?
> 
> http://stackoverflow.com/questions/18275662/python-nodetransformer-how-to-
remove-nodes

As Chris says, you are overriding too much of the generic behaviour. Here is 
a working demo:

import ast

class MyTransformer(ast.NodeTransformer):
    def visit_For(self, node):
        """
        For nodes: replace with nothing
        """
        print("removing a For node")
        return None


source = """
l = [0, 1, 2, 3]

total = 0

for i in l:
    total += i

print(total)
"""

transformer = MyTransformer()
module = ast.parse(source)
transformer.visit(module)
codeobj = compile(module, '<string>', 'exec')
exec(codeobj)





More information about the Python-list mailing list