Python 3, Are there any known security holes in ast.literal_eval(node_or_string)?

The documentation states it is safe, and there is no bug relative to security of literal_eval in the bug tracker, so you can probably assume it is safe. Also, according to the source, literal_eval parses the string to a python AST (source tree), and returns only if it is a literal. The code is never … Read more

Constructing an Abstract Syntax Tree with a list of Tokens

The fundamental trick is to recognize that parsing, however accomplished, happens in incremental steps, including the reading of the tokens one by one. At each incremental step, there is an opportunity to build part of the AST by combining AST fragments built by other incremental steps. This is a recursive idea, and it bottoms out … Read more

Malformed String ValueError ast.literal_eval() with String representation of Tuple

ast.literal_eval (located in ast.py) parses the tree with ast.parse first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add Decimal to the code you need to copy all the code … Read more

What’s the difference between parse trees and abstract syntax trees (ASTs)?

This is based on the Expression Evaluator grammar by Terrence Parr. The grammar for this example: grammar Expr002; options { output=AST; ASTLabelType=CommonTree; // type of $stat.tree ref etc… } prog : ( stat )+ ; stat : expr NEWLINE -> expr | ID ‘=’ expr NEWLINE -> ^(‘=’ ID expr) | NEWLINE -> ; expr … Read more

Simple example of how to use ast.NodeVisitor?

ast.visit — unless you override it in a subclass, of course — when called to visit an ast.Node of class foo, calls self.visit_foo if that method exists, otherwise self.generic_visit. The latter, again in its implementation in class ast itself, just calls self.visit on every child node (and performs no other action). So, consider, for example: … Read more