Codectionary / Developer documentation / Python

ast.literal_eval(): parse literal data

Read a restricted Python literal representation without evaluating arbitrary Python expressions.

How it works

literal_eval accepts Python literal structures such as strings, numbers, tuples, lists, dictionaries, sets, booleans and None. It does not run general function calls or resolve arbitrary variable names.

This is a parser for Python literal notation, not JSON and not a general expression calculator. It does not validate that the parsed object has the shape or types your application expects.

Limitations and practical choices

Do not use eval to parse data. literal_eval avoids general code execution, but is not safe for arbitrary untrusted input: resource exhaustion or interpreter stack exhaustion remain possible.

Prefer a defined interchange format such as JSON for external interfaces, impose appropriate resource limits, and validate the resulting data. A small length check alone is not a complete sandbox.

Try it yourself

Parse a controlled tuple representation, verify it has exactly two integers, and reject a list with a different shape. Explain why parsing and validation are separate.

Syntax

from ast import literal_eval
value = literal_eval("[1, 2, 3]")

Examples

Parse a controlled list

Convert a literal representation into actual data.

from ast import literal_eval
values = literal_eval("[2, 4, 6]")
print(type(values).__name__)
print(sum(values))
  1. literal_eval recognises the list and integer literals. The result is a list object, so sum adds its numeric elements.
  2. No application function calls are evaluated from the text. The example uses a small fixed input whose shape is known.
  3. This can help import trusted legacy Python-style data; it is not a replacement for external-input validation.
  4. Expected output: list 12

Reject an expression

Show that a computation is outside the accepted format.

from ast import literal_eval
try:
    literal_eval("1 + 2")
except (ValueError, SyntaxError):
    print("Expected literal data")
  1. General arithmetic expressions are not accepted as ordinary literal data. The parser rejects this text rather than calculating three.
  2. The handler catches the expected parse rejection classes. It does not attempt to recover by calling eval.
  3. A file format should state whether it contains data or executable expressions; silently switching between them is dangerous.
  4. Expected output: Expected literal data

Validate after parsing

Check the shape before using the values.

from ast import literal_eval
value = literal_eval("(3, 5)")
if (isinstance(value, tuple) and len(value) == 2
        and all(type(item) is int for item in value)):
    print("Coordinates:", value[0], value[1])
else:
    print("Invalid coordinates")
  1. The checks establish a tuple of length two before the values are used. Exact int checks intentionally exclude bool, which is an int subclass.
  2. Parsing alone would also accept many other literal shapes. The application supplies the narrower coordinate contract.
  3. For real untrusted input, use a resource-bounded parsing strategy as well as a schema check.
  4. Expected output: Coordinates: 3 5

Best practices

  • Do not use eval to parse data. literal_eval avoids general code execution, but is not safe for arbitrary untrusted input: resource exhaustion or interpreter stack exhaustion remain possible.
  • Prefer a defined interchange format such as JSON for external interfaces, impose appropriate resource limits, and validate the resulting data. A small length check alone is not a complete sandbox.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading