lundi 26 décembre 2016

using ast module to transform random constants in Python source

I'm interested in writing a program that uses Python's built-in AST module to randomly modify constants in arbitrary Python source.

This transformation will likely involve a traversal of the abstract syntax tree representation using operations defined by the AST module. The module offers two options: first, ast.walk() returns references to all nodes in the AST, but does not offer any contextual information, making reassembling the tree impossible. Secondly, the documentation describes a second method involving the ast.NodeTransformer class: several sources of documentation describe generally how to use NodeTransformer.

However, the NodeTransformer documentation fails to mention how to randomly apply conditional substitutions to the AST. Specifically, I would like to modify this feature to create a function that selects a random node in the ast, chooses a constant associated with the node at random, and replace that constant with a randomly selected constant of the same type.

I suspect that I'm struggling to understand how to properly modify NodeTransformer because I rarely program in an object oriented style (usually adhering to the functional paradigm). Hopefully pointing me in the right direction will come easily to one of you.




Aucun commentaire:

Enregistrer un commentaire