Python ast - parse, walk, and safely evaluate Python syntax
Answer: Parse the source into an AST node with ast.parse(). ast.literal_eval() evaluates an expression node or a string containing only a Python literal or container display.
Examples
import ast
tree = ast.parse("x = 1 + 2")
print(ast.dump(tree, indent=2))
print(ast.unparse(tree))
print(ast.literal_eval("{'retries': 3, 'names': ['a', 'b']}"))
# ast.literal_eval("os.system('rm -rf /')") # ValueError: malformed node
class Names(ast.NodeVisitor):
def visit_Name(self, node):
print(node.id, type(node.ctx).__name__)
self.generic_visit(node)
Names().visit(tree)
Rules
literal_evalis for a Python literal or container display, not a general expression.NodeVisitorwalks the tree and calls a visitor function for every node found.ast.unparse()generates source from a tree.
See also
Claims
- id: C1 claim: parse builds an AST from source. source: S1 evidence: "Parse the source into an AST node"
- id: C2 claim: literal_eval evaluates only Python literals. source: S1 evidence: "Evaluate an expression node or a string containing only a Python literal"
- id: C3 claim: literal_eval evaluates an expression node or a literal string. source: S2 evidence: "Evaluate an expression node or a string containing"
Sources
- [S1] ast - Abstract Syntax Trees. Python docs. https://docs.python.org/3/library/ast.html . License: PSF-2.0. Accessed 2026-11-18.
- [S2] Lib/ast.py. python/cpython (GitHub). https://github.com/python/cpython/blob/main/Lib/ast.py . License: PSF-2.0. Accessed 2026-11-18.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, ast - Abstract Syntax Trees; python/cpython (GitHub), Lib/ast.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, ast - Abstract Syntax Trees; python/cpython (GitHub), Lib/ast.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.
Cite this
iinventedlight. 2026. "Python ast - parse, walk, and safely evaluate Python syntax." iinventedlight Library, iil:note:c46kkt4b, version of 2026-11-18. https://iinventedlight.com/library/notes/python-ast/. License: CC-BY-4.0.
@misc{iil_note_c46kkt4b,
author = {{iinventedlight}},
title = {{Python ast - parse, walk, and safely evaluate Python syntax}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-18},
url = {https://iinventedlight.com/library/notes/python-ast/},
note = {Permanent ID iil:note:c46kkt4b. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).
For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-ast.md.