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.
Code
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
astmust 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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Are there third-party dependencies?
- `ast` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.