On this page
ast.literal_eval
Prev: ast.iter_fields | Up: ast | Next: ast.main
Rel: ast.Add, ast.alias, ast.And, ast.AnnAssign
Ref: docs.python.org — ast.literal_eval
Tags: #public #python3 #stdlib #ast
Import
import ast
from ast import literal_eval
Signature & Overview
ast.literal_eval(node_or_string)
Evaluate an expression node or a string containing only a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
Usage
import ast
val = ast.literal_eval("{'a': [1, 2, True, None]}")
assert val == {"a": [1, 2, True, None]}
Gotchas
- Safe alternative to
eval()for Python literals: Rejects function calls, attribute lookups, and comprehensions withValueError—still avoid passing untrusted mega-nested strings that could hit recursion limits.
REPL Inspect
from ast import literal_eval
help(literal_eval)
Linked from
Related notes
- tuts/python3/stdlib_module/ast/iter_fields Linked here; links to this page; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/main Linked here; links to this page; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/Add Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/alias Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/And Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/AnnAssign Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/AST Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ast/arg shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/arguments shared tags: #ast, #stdlib