← All notes

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

See also

Claims

Sources

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

Permanent ID: iil:note:c46kkt4b

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.},
}

Markdown

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.