Trusted answers to developer questions

What is ast.literal_eval(node_or_string) in Python?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

Python ast module

The ast module (Abstract Syntax Tree)tree representation of source code allows us to interact with and modify Python code. Python comes with abstract syntax grammar that is subject to change with every Python release.

The ast module helps applications to process trees of syntax and find out what current syntax grammar looks like programmatically. Abstract syntax trees are great tools for program analysis and program transformation systems.

ast.literal_eval method

The ast.literal_eval method is one of the helper functions that helps traverse an abstract syntax tree. This function evaluates an expression node or a string consisting of a Python literal or container display.

The ast.literal_eval method can safely evaluate strings containing Python values from unknown sources without us having to parse the values.

Note: Complex expressions involving indexing or operators cannot be evaluated using this function.

Parameters

node_or_string: The node or string that is to be evaluated. It may consist of the following Python literal structures:

  • strings
  • bytes
  • numbers
  • tuples
  • lists
  • dicts
  • sets
  • booleans
  • None and Ellipsis.

Let's see examples of using ast.literal_eval():

String containing Python literal

The method returns a list object.

import ast
string_l = "[3, 2, 3, 4]"
list_object = ast.literal_eval(string_l)
print(list_object)
print(type(list_object))

Explanation

  • Line 3: We create a Python literal string_l .

  • Line 4: We pass the literal to the ast.literal_eval() method to get a list object.

String containing Python dictionary

The following Python code illustrates how we evaluate a string containing dictionary with the ast.literal_eval helper method:

import ast
dictionary = ast.literal_eval("{'a': 1, 'b': 2}")
print (type(dictionary))
print (dictionary)

Explanation

  • Line 2: the ast.literal_eval method successfully evaluates the string, and gets the Python dictionary object.

String containing a Python numeric literal

The following Python code illustrates how we evaluate a string containing numeric literal with the ast.literal_eval helper method:

import ast
num = "29"
number_object = ast.literal_eval(num)
print(number_object)
print(type(number_object))

Explanation

  • Line 2: The ast.literal_eval method successfully evaluates the string, and gets the Python object.

RELATED TAGS

python3
abstractsyntaxtree
Did you find this helpful?