0

I have a Python AST that I'd like to traverse breadth first. ast.walk appears to do the trick, but from its documentation

ast.walk(node)

Recursively yield all descendant nodes in the tree starting at node (including node itself), in no specified order. This is useful if you only want to modify nodes in place and don’t care about the context.

one might assume that this is merely an implementation detail. Is there a traversal method that guaranteed breadth-first?

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
  • Does this answer your question? [What type of tree traversal does the ast module use?](https://stackoverflow.com/questions/22646543/what-type-of-tree-traversal-does-the-ast-module-use) – Neervana Jan 06 '23 at 12:38
  • @Neervana No, it doesn't. The question simply states the fact that `walk` currently is breadth-first, as I already stated in my question. I'm looking for a way that can be _relied_ on. – Nico Schlömer Jan 06 '23 at 16:15
  • 1
    If you want to be SURE that it's a BFS, the only way would be to access the children of every node and implement it yourself, otherwise, it would make sense to assume that ` walk` is pretty reliable, since the implementation hasn't changed in 9 years (and searching an AST in DFS does not really make sense) – Neervana Jan 06 '23 at 16:34
  • 2
    @Neervana: the fact that NodeVisitor is DFS seems to indicate that DFS traverses do sometimes make sense. Anyway, ast.walk is about six lines of code, which you could copy into your program if you are worried about it someday changing. – rici Jan 07 '23 at 02:57

0 Answers0