title: using ast module to transform random constants in Python source
body: <p>I'm interested in writing a program that uses Python's built-in <a href="https://docs.python.org/2/library/ast.html" rel="nofollow noreferrer">AST module</a> to randomly modify constants in arbitrary Python source.</p>
  
  <p>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, <a href="https://docs.python.org/2/library/ast.html?highlight=walk#ast.walk" rel="nofollow noreferrer">ast.walk()</a> 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 <a href="https://docs.python.org/2/library/ast.html?highlight=nodetransformer#ast.NodeTransformer" rel="nofollow noreferrer">ast.NodeTransformer</a> class: several sources of <a href="https://greentreesnakes.readthedocs.io/en/latest/manipulating.html#modifying-the-tree" rel="nofollow noreferrer">documentation</a> describe generally how to use NodeTransformer.</p>
  
  <p>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 <strong>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.</strong></p>
  
  <p>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.</p>