What is ast.literal_eval(node_or_string) in Python?
Python ast module
The ast module
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:
stringsbytesnumberstupleslistsdictssetsbooleansNoneandEllipsis.
Let's see examples of using ast.literal_eval():
String containing Python literal
The method returns a list object.
import aststring_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 astdictionary = ast.literal_eval("{'a': 1, 'b': 2}")print (type(dictionary))print (dictionary)
Explanation
- Line 2: the
ast.literal_evalmethod 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 astnum = "29"number_object = ast.literal_eval(num)print(number_object)print(type(number_object))
Explanation
Line 2: The
ast.literal_evalmethod successfully evaluates the string, and gets the Python object.