Python AST NodeTransformer: Return multiple nodes

Viewed 1195

Is there an easy way to return multiple nodes to replace a single node when using the ast.NodeTransformer? For example, say I want to rewrite all expressions of the form

f(g()) to _x1 = g(); g(_x1)

It would be quite easy to do this if visit_Expr could return multiple, rather than a single node. I couldn't seem to get that to work though, so I assume this is not the way to do this. Any suggestions would be much appreciated.

[Update] As an update, I have a working version of this that accumulates the new and old nodes in a list, and assigns them to the body of the enclosing scope node (e.g. For, While, Module node etc). This is definitely a hacky way of doing it, and suspect there is a better way out there. I'll keep this around in case someone knows of that way.

[final update] looking at the docs for NodeTransformer it's actually entirely possible to return a list of nodes, if the node is part of a collection of statements.

1 Answers
Related