samedi 18 avril 2020

Should I use `NodeVisitor` to traverse/modify/analyze Python AST?

The Python's stdlib package ast recommends to use NodeVisitor class in order to do something with AST.

It seems like in every programmer's mind (not only pythonista) a "Visitor" pattern (as described in GOF) is associated with traversal of hierarchical data structures, like trees. It feels very naturally to "visit" node after node.

But in essence a "Visitor" pattern was invented to solve completely different, very particular problem - to implement double dispatch in languages which lacks native support of it, like C++ and Java (and Python, as well).

Here is very good explanation of the problem and the solution: https://eli.thegreenplace.net/2016/a-polyglots-guide-to-multiple-dispatch

So the question is should I even bother with suggested approach? Personally I found myself very difficult in understanding a NodeVisitor subclass implementation. What are another techniques can be used to AST things?

Aucun commentaire:

Enregistrer un commentaire