Python Glossary Русский

all Python 3astfunction

ast.literal_eval()

helper functions

Evaluates a string that holds only Python literals: numbers, strings, lists, dicts, sets, tuples, True/False/None. The replacement for eval when parsing data.

Syntax

ast.literal_eval(node_or_string)

Unlike eval, it runs no code: no names, calls or imports, so "__import__('os').system(...)" raises ValueError instead of running a command. There is no arithmetic either: '2**10' and even '1+2' raise ValueError (only addition and subtraction for complex literals like '1+2j' and '1-2j' are allowed). It is safe from code execution but not from resource abuse: huge or deeply nested input can exhaust memory or the stack, so cap the length of untrusted input; for data exchange json.loads is usually the better fit.

Examples

import ast
data = ast.literal_eval("{'a': [1, 2], 'b': (3, None)}")
print(data['a'], data['b'])  # → [1, 2] (3, None)
print(ast.literal_eval('set()'), ast.literal_eval('  42'))  # → set() 42
import ast
for text in ["__import__('os')", '2**10', 'x']:
    try:
        ast.literal_eval(text)
    except ValueError as e:
        print(type(e).__name__)  # → ValueError / ValueError / ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy