literal_eval Parses Literals Only

literal_eval parses literal data — lists, dicts, tuples, strings — and refuses calls, arithmetic, and name lookups with ValueError instead of running them.

PythonSecurity Boundaries

Code

snippet
from ast import literal_eval

# literal_eval accepts literal data only: numbers, strings, tuples, lists,
# dicts, sets, booleans, None
print(literal_eval("[1, 2, 3]"))
print(literal_eval("{'mode': 'fast', 'retries': 3}"))
print(literal_eval("(0.5, 0.25)"))
print(literal_eval("'plain string'"))

# Anything that would execute code or reference names is refused
for payload in (
    "__import__('os').system('id')",
    "open('secrets.txt').read()",
    "1 + 1",
    "config['key']",
):
    try:
        literal_eval(payload)
    except ValueError:
        print("rejected:", payload, "->", ValueError.__name__)

# Mind the boundary: it parses text into Python values, it does not validate
# them — type checks belong in the layer above
value = literal_eval("{'retries': 'three'}")
print("parsed despite odd types:", value)

What the code does

Repetition is confined to for payload in ( — the rest of the file is straight-line. The snippet’s external surface is literal_eval, all of it via ast.

Top-level bindings value hold the demo state — nothing sits inside a function scope.

Watch out for

  • ast must be installed first — the snippet imports it directly.

Applying it

Look for the rejected:, parsed despite odd types: prefixes when the file runs; they tie each line to its step.

Statements that matter

except ValueError:
    print("rejected:", payload, "->", ValueError.__name__)

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`ast` — install it with the package manager before running.