ast
moduleThe 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
methodThe 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.
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()
:
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))
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.
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)
ast.literal_eval
method successfully evaluates the string, and gets the Python dictionary object.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))
Line 2: The ast.literal_eval
method successfully evaluates the string, and gets the Python object.